import { sceneData, sceneCustomizedData } from '/utils/datas/sceneData';
import TWEEN from './tween.js';
import * as THREE from './three.js';

import GLTFLoader from './GLTFLoader.js';
import JSZip from './jszip.min.js'

var new_zip = new JSZip();
var that;
var canvas;
var gl;
var Screen_Width = 0;
var ZW_Scene;
var ZW_Camera;
var ZW_Renderer;
var ZW_BACK_COLOR = 0xffffff;
var ZW_BACK_ALPHA = 1.0;

var ZW_FinishSceneBox;
var ZW_SceneSize;
var ZW_PrimitiveViewDistance = 2.7;

var ZW_normalCamera;    //常规操作的相机

var ZW_CenterNode0;
var ZW_CenterNode;
var ZW_CameraNode;
var ZW_SceneParent;
var ZW_SelectParent;

var ZW_Platform;
var ZW_PixelRatio = 1;
var ZW_Width1 = 0;
var ZW_Height1 = 0;

var ZW_raycaster; //用于碰撞检测

var ZW_GlbNode;

var CurrentIndex = 0;
var LastIndex = 0;

var ZW_ProcessValue = 0;

var STATE = {
  NONE: -1,
  TOUCH_ROTATE: 0,
  TOUCH_ZOOM_PAN: 1,
  TOUCH_PAN: 2
};

var _state = STATE.NONE;
var _movePrev = new THREE.Vector2();
var _moveCurr = new THREE.Vector2();
var _touchZoomDistanceStart = 1;
var _touchZoomDistanceEnd = 1;
var _panStart = new THREE.Vector2();
var _panEnd = new THREE.Vector2();

var ZW_ProcessNum = 40;
var PLATFORM = "TAOBAO";
var ZW_HandValue = 8.0;

var timestamp = 0;
var ZW_Timer;

var showTime = 0;

const HIDE_TIME = 5000;
var TabState = true;

var myIndex = 0;
var nameArray = ['S4', 'S5', 'S6', 'S7', 'S8', 'S9'];

var document = {};
document.createElementNS = function (ns, tagName) {
  if (tagName === 'canvas') {
    return null;
  } else if (tagName === 'img' && PLATFORM === 'TAOBAO') {
    return canvas.createImage();
  } else if (tagName === 'img' && PLATFORM === 'H5') {
    let image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    return image;
  }

  return null;
}

//加载回调
function OnModelProcess(value) {
  console.log(value);
}

//加载完成
function OnModelEnd() {
  // my.alert({
  //       content: '加载完成',
  //       buttonText: '好',
  //       success: () => {
  //       },
  //     });
}


let cax = require("./cax/index");
var that;
var ZW_Width0 = 0;
var ZW_Width = 0;
var ZW_Height = 0;
var ZW_PixelRatio = 1;

var ZW_PicGroup;
var ZW_BackImg;
var CurrentPicTag = '';
var Last_Pos = [0, 0];
var ZW_Text_Control = true;  //文字拖动约束，false可以任意拖动，true为只可在框内上下拖动
var Drag_Type = 'pic';

var Rect_Data = []; //虚线框数据
var Text_Data = []; //文字框数据

var ZW_Need_Update = false;

var StartSliderValue = 0;
var ctx0;

// 网格数 从配置数据获取
var g_hGridNum;
var g_vGridNum;
// 网格宽度 计算得
var g_gridWidth;

// 内网格线group
var g_gridGroup;
// 外网格线group
var g_gridBorderGroup;
// 内容区域group
var g_contentAreasGroup;
// 选中的场景数据
var g_selectedSceneData = sceneCustomizedData[0];

var g_elementPadding = 10;


// test param
var t_selectAreaId;
var t_picSum = 0;
var t_textSum = 0;

//隐藏或者显示图片
function SetPicVisible(tag, visible) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      ZW_PicGroup.children[i].visible = visible;
      ShowProcess();
      return;
    }
  }
}

//画面更新
function ShowProcess(time) {
  //console.log(time);
  if (!time) time = 100;
  var tim = setTimeout(function () {
    that.ctx.clearRect(0, 0, ZW_Width, ZW_Height);
    that.stage.update();
    clearTimeout(tim);
  }, time);
}

//添加可拖动图片 
function AddPic(tag, x, y, width, height, url) {
  var picGroup = new cax.Group();
  //picGroup.x = 100;
  // picGroup.scaleX = 0.5;
  // picGroup.scaleY = 0.5;
  // picGroup.originX = width/2
  // picGroup.originY = height/2 
  picGroup.alpha = 1.0
  picGroup.x = x + width / 2;
  picGroup.y = y + height / 2;
  picGroup.originX = x + width / 2;
  picGroup.originY = y + height / 2;

  picGroup.tag = tag;
  const img = new cax.Bitmap(url, null, width, height);
  img.x = x;
  img.y = y;
  img.rect = [0, 0, width, height];
  img.tag = 'img';

  picGroup.add(img);

  var rect = new cax.Rect(width, height, {
    lineWidth: 1,
    strokeStyle: "#0A603F"
  });
  rect.x = x;
  rect.y = y + 2;
  rect.width = width;
  rect.height = height;
  rect.tag = 'rect';
  picGroup.add(rect);
  //console.log(picGroup);

  const img1 = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/touming.png', null, 2, 2);
  img1.x = x - 1;
  img1.y = y - 1;
  img1.rect = [0, 0, 2, 2];
  img1.tag = 'i1';
  picGroup.add(img1);

  const img2 = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/touming.png', null, 2, 2);
  img2.x = x + width - 1;
  img2.y = y - 1;
  img2.rect = [0, 0, 2, 2];
  img2.tag = 'i2';
  picGroup.add(img2);

  const img3 = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/touming.png', null, 2, 2);
  img3.x = x - 1;
  img3.y = y + height - 1;
  img3.rect = [0, 0, 2, 2];
  img3.tag = 'i3';
  picGroup.add(img3);

  const img4 = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/touming.png', null, 2, 2);
  img4.x = x + width - 1;
  img4.y = y + height - 1;
  img4.rect = [0, 0, 2, 2];
  img4.tag = 'i4';
  picGroup.add(img4);


  const rImg = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/remove.png', null, 36, 36);
  rImg.x = x + width - 12 * 1.5;
  rImg.y = y - 12 * 1.5;
  rImg.rect = [0, 0, 24 * 1.5, 24 * 1.5];
  rImg.scaleX = 1.5;
  rImg.scaleY = 1.5;
  rImg.tag = 'remove';
  picGroup.add(rImg);

  const sImg = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/scale.png', null, 36, 36);
  sImg.x = x - 12 * 1.5;
  sImg.y = y + height - 12 * 1.5;
  sImg.rect = [0, 0, 24 * 1.5, 24 * 1.5];
  sImg.scaleX = 1.5;
  sImg.scaleY = 1.5;
  sImg.tag = 'scale';
  picGroup.add(sImg);

  rect.visible = false;
  rImg.visible = false;
  sImg.visible = false;
  //console.log(picGroup);
  ZW_PicGroup.add(picGroup);

  img.on('touchStart', () => {
    //console.log(img);
    SetSelectPic(tag);
    CurrentPicTag = tag;
    Drag_Type = 'pic';
  });

  rect.on('touchStart', (event) => {
    SetSelectPic(tag);
    CurrentPicTag = tag;
    Drag_Type = 'pic';

  });

  rImg.on('touchStart', () => {
    RemovePic(tag);
    SetSliderValue(0);
  });

  sImg.on('touchStart', (event) => {
    //console.log('s');
    Drag_Type = 'scale';
    // event.changedTouches[0].x = event.changedTouches[0].x*2;
    // event.changedTouches[0].y = event.changedTouches[0].y*2;

    //Last_Scale_Pos = [event.stageX,event.stageY];
  });

  for (var i = 0; i < 5; i++) {
    ShowProcess(500 * i);
  }

}

function getPicElement(tag) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      return ZW_PicGroup.children[i];
    }
  }
  return null;
}

function getElementFromParent(parentElement, tag) {
  for (var i = 0; i < parentElement.children.length; i++) {
    if (parentElement.children[i].tag == tag) {
      return parentElement.children[i];
    }
  }
  return null;
}

//获取图片类型，判断是否为文字
function GetPicType(tag) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      for (var j = 0; j < ZW_PicGroup.children[i].children.length; j++) {
        if (ZW_PicGroup.children[i].children[j].tag == 'text') {
          return 'text';
        }
      }
    }
  }
  return 'pic';
}

//更新文字
function UpdateText(tag, textList) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      let textGroup = ZW_PicGroup.children[i];
      for (var m = 0; m < textGroup.children.length; m++) {
        let text = textGroup.children[m];
        if (text.tag.indexOf("text-content-") >= 0 && m < textList.length) {
          text.text = textList[m];
        }
      }
    }
  }
  ShowProcess();

}
// ZW_PicGroup.children[i].children[j].text = text;
//添加文字
function AddText(tag, x, y, width, height, text) {
  var picGroup = new cax.Group();
  picGroup.alpha = 1.0
  picGroup.x = x + width / 2;
  picGroup.y = y + height / 2;
  picGroup.originX = x + width / 2;
  picGroup.originY = y + height / 2;

  //picGroup.rotation = 60;

  picGroup.tag = tag;


  const img = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/touming.png', null, width, height);
  img.x = x;
  img.y = y;
  img.rect = [0, 0, width, height];
  img.tag = 'img1';

  picGroup.add(img);

  const img1 = new cax.Text(text, {
    font: '20px Arial',
    color: '#ffffff',
    maxWidth: width,
    baseline: 'middle',
    textAlign: 'center'
  });
  img1.x = x + width / 2;
  img1.y = y + height / 2;
  img1.width = width;
  img1.height = height;
  img1.tag = 'text';
  picGroup.add(img1);

  var rect = new cax.Rect(width, height, {
    lineWidth: 1,
    strokeStyle: "#0A603F"
  });
  rect.x = x;
  rect.y = y + 2;
  rect.width = width;
  rect.height = height;
  rect.tag = 'rect';
  picGroup.add(rect);

  const rImg = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/remove.png', null, 36, 36);
  rImg.x = x + width - 12 * 1.5;
  rImg.y = y - 12 * 1.5;
  rImg.rect = [0, 0, 24 * 1.5, 24 * 1.5];
  rImg.scaleX = 1.5;
  rImg.scaleY = 1.5;
  rImg.tag = 'remove';
  picGroup.add(rImg);

  const sImg = new cax.Bitmap('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/scale.png', null, 36, 36);
  sImg.x = x - 12 * 1.5;
  sImg.y = y + height - 12 * 1.5;
  sImg.rect = [0, 0, 24 * 1.5, 24 * 1.5];
  sImg.scaleX = 1.5;
  sImg.scaleY = 1.5;
  sImg.tag = 'scale';
  //picGroup.add(sImg);

  rect.visible = false;
  rImg.visible = false;
  sImg.visible = false;
  ZW_PicGroup.add(picGroup);



  img.on('touchStart', () => {
    //console.log(img);
    SetSelectPic(tag);
    CurrentPicTag = tag;
    Drag_Type = 'pic';
  });

  rect.on('touchStart', (event) => {
    // SetSelectPic(tag);
    CurrentPicTag = tag;
    Drag_Type = 'pic';

  });

  rImg.on('touchStart', () => {
    RemovePic(tag);
    SetSliderValue(0);
  });


  // sImg.on('touchStart', (event) => {
  //   Drag_Type = 'scale';
  // });
  //  
  // img.initAABB();

  ShowProcess();

}

//只画框
function SetSelectPic0(tag, mode) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      for (var j = 0; j < ZW_PicGroup.children[i].children.length; j++) {
        if (ZW_PicGroup.children[i].children[j].tag == 'rect' || ZW_PicGroup.children[i].children[j].tag == 'scale' || ZW_PicGroup.children[i].children[j].tag == 'remove') {
          ZW_PicGroup.children[i].children[j].visible = true;
        }
      }

    }
  }
  ShowProcess();
  return;
}

//设置图片状态
function SetSelectPic(tag, mode) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      for (var j = 0; j < ZW_PicGroup.children[i].children.length; j++) {
        // debugger;
        let item = ZW_PicGroup.children[i].children[j];
        if (ZW_PicGroup.children[i].children[j].tag == 'bounds'
          || ZW_PicGroup.children[i].children[j].tag == 'remove') {
          ZW_PicGroup.children[i].children[j].visible = true;

          // SetSliderValue(GetPicRotation(tag));
        }
      }

    } else {
      for (var j = 0; j < ZW_PicGroup.children[i].children.length; j++) {
        if (ZW_PicGroup.children[i].children[j].tag == 'bounds'
          || ZW_PicGroup.children[i].children[j].tag == 'remove') {
          ZW_PicGroup.children[i].children[j].visible = false;
        }
      }
    }
  }
  //  
  //  
  ShowProcess();
  return;
}

//删除图片
function RemovePic(tag) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      // ZW_PicGroup.children[i].visible = true;
      // ZW_PicGroup.children[i].x += 100;
      //ZW_PicGroup.remove(ZW_PicGroup.children[i]);
      // for(var j=0; j<ZW_PicGroup.children[i].children.length; j++)
      // {

      //   ZW_PicGroup.children[i].remove(ZW_PicGroup.children[i].children[j]);
      // }
      ZW_PicGroup.remove(ZW_PicGroup.children[i]);

      ShowProcess();
      return;
    }
  }

}

//设置图片旋转值
function SetPicRotation(tag, value) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      ZW_PicGroup.children[i].rotation = value;

      ShowProcess();
      return;
    }
  }

}

//获取图片旋转值
function GetPicRotation(tag) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      return ZW_PicGroup.children[i].rotation;
    }
  }
}


//设置图片位置
function SetPicPosition(tag, x, y) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      ZW_PicGroup.children[i].x = x;
      ZW_PicGroup.children[i].y = y;

      that.ctx.clearRect(0, 0, ZW_Width, ZW_Height);
      that.stage.update();
      return;
    }
  }
}

//获取图片大小
function GetPicScale(tag) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      return ZW_PicGroup.children[i].scaleX;
    }
  }
}


//设置图片大小
function SetPicScale(tag, value) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      ZW_PicGroup.children[i].scaleX = value;
      ZW_PicGroup.children[i].scaleY = value;

      ShowProcess();
      return;
    }
  }
}

//碰撞检测
function CollisionDetection0() {

  that.stage.updateAABB();
  var collistionArray = [];
  var tagArray = [];
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    for (var j = 0; j < ZW_PicGroup.children[i].children.length; j++) {
      if (ZW_PicGroup.children[i].children[j].tag == 'img') {

        if (ZW_PicGroup.children[i].children[j].parent.tag == 'tag0') {
          console.log(ZW_PicGroup.children[i].children[j].parent);
        }
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;
        collistionArray.push(tmpBox);
        //console.log(ZW_PicGroup.children[i].children[j].parent.tag);
        //console.log(ZW_PicGroup.children[i].children[j]);
        tagArray.push(ZW_PicGroup.children[i].children[j].parent.tag);
      }
      if (ZW_PicGroup.children[i].children[j].tag == 'i1') {
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;
        console.log(tmpBox);
      }

      if (ZW_PicGroup.children[i].children[j].tag == 'img1') {

        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;
        for (var k = 0; k < ZW_PicGroup.children[i].children.length; k++) {
          if (ZW_PicGroup.children[i].children[k].tag == 'text') {
            //console.log(ZW_PicGroup.children[i].children[k].text);
            var RespMemo = ZW_PicGroup.children[i].children[k].text;   //定义字符串

            var re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则
            var re1 = /[a-z]/g;  //小写字母
            var re2 = /[A-Z]/g;  //大写字母
            //console.log(RespMemo.match(re1));
            var leng = RespMemo.match(re) ? RespMemo.match(re).length : 0;  //计算中文的个数
            var leng1 = RespMemo.match(re1) ? RespMemo.match(re).length : 0;  //计算小写字母的个数
            var leng2 = RespMemo.match(re2) ? RespMemo.match(re).length : 0;  //计算大写字母的个数

            // console.log(leng);
            // console.log(leng1);
            // console.log(leng2);

            var wordWidth = leng * 20 + leng1 * 10 + leng2 * 15;
            //console.log(tmpBox);
            tmpBox[0] = tmpBox[0] + tmpBox[2] * 0.5 - wordWidth * 0.5;
            tmpBox[2] = wordWidth;
            //console.log(tmpBox);
          }

        }
        collistionArray.push(tmpBox);
        //console.log('img1');
        //console.log(ZW_PicGroup.children[i].children[j]);
        tagArray.push(ZW_PicGroup.children[i].children[j].parent.tag);
      }

    }
  }
  console.log(collistionArray);
  console.log(tagArray);

  var bColl = false;
  for (var i = 0; i < collistionArray.length; i++) {
    var BoxMinX1 = collistionArray[i][0];
    var BoxMinY1 = collistionArray[i][1];
    var BoxMaxX1 = collistionArray[i][0] + collistionArray[i][2];
    var BoxMaxY1 = collistionArray[i][1] + collistionArray[i][3];

    for (var j = 0; j < collistionArray.length; j++) {
      if (i != j) {
        var BoxMinX2 = collistionArray[j][0];
        var BoxMinY2 = collistionArray[j][1];
        var BoxMaxX2 = collistionArray[j][0] + collistionArray[j][2];
        var BoxMaxY2 = collistionArray[j][1] + collistionArray[j][3];


        //console.log(collistionArray);
        bColl = BoxMaxX1 < BoxMinX2 || BoxMinX1 > BoxMaxX2 || BoxMaxY1 < BoxMinY2 || BoxMinY1 > BoxMaxY2 ? false : true;
        if (bColl) {
          SetSelectPic('');
          SetSelectPic0(tagArray[i]);
          SetSelectPic0(tagArray[j]);
          return [bColl, tagArray[i], tagArray[j]];
        }
      }
    }
  }

  // var rect = new cax.Rect(150, 150, {
  //   lineWidth: 4,
  //   strokeStyle: "#ff0000"
  // }); 
  // rect.x = 100; 
  // rect.y = 100;  
  // rect.width = 150;
  // rect.height = 150;
  // that.stage.add(rect);
  // ShowProcess();

  return [bColl];

  console.log(BoxMinX1 + ',' + BoxMinY1 + ',' + BoxMaxX1 + ',' + BoxMaxY1);
  console.log(BoxMinX2 + ',' + BoxMinY2 + ',' + BoxMaxX2 + ',' + BoxMaxY2);

  return BoxMaxX1 < BoxMinX2 || BoxMinX1 > BoxMaxX2 ||
    BoxMaxY1 < BoxMinY2 || BoxMinY1 > BoxMaxY2 ? false : true;
  //console.log(collistionArray);
}

//线段相交判断
function JudgeIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {

  //快速排斥：
  //两个线段为对角线组成的矩形，如果这两个矩形没有重叠的部分，那么两条线段是不可能出现重叠的

  //这里的确如此，这一步是判定两矩形是否相交
  //1.线段ab的低点低于cd的最高点（可能重合）
  //2.cd的最左端小于ab的最右端（可能重合）
  //3.cd的最低点低于ab的最高点（加上条件1，两线段在竖直方向上重合）
  //4.ab的最左端小于cd的最右端（加上条件2，两直线在水平方向上重合）
  //综上4个条件，两条线段组成的矩形是重合的
  //特别要注意一个矩形含于另一个矩形之内的情况

  if (!(Math.min(x1, x2) <= Math.max(x3, x4) && Math.min(y3, y4) <= Math.max(y1, y2) && Math.min(x3, x4) <= Math.max(x1, x2) && Math.min(y1, y2) <= Math.max(y3, y4)))
    return false;

  //跨立实验：
  //如果两条线段相交，那么必须跨立，就是以一条线段为标准，另一条线段的两端点一定在这条线段的两段
  //也就是说a b两点在线段cd的两端，c d两点在线段ab的两端
  var u, v, w, z
  u = (x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1);
  v = (x4 - x1) * (y2 - y1) - (x2 - x1) * (y4 - y1);
  w = (x1 - x3) * (y4 - y3) - (x4 - x3) * (y1 - y3);
  z = (x2 - x3) * (y4 - y3) - (x4 - x3) * (y2 - y3);
  return (u * v <= 0.00000001 && w * z <= 0.00000001);
}

//碰撞检测
function CollisionDetection() {

  that.stage.updateAABB();
  var pArray1 = [];
  var pArray2 = [];
  var pArray3 = [];
  var pArray4 = [];
  var collistionArray = [];
  var collistionArray1 = [];
  var tagArray = [];
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    var tmpPointArray = [];
    for (var j = 0; j < ZW_PicGroup.children[i].children.length; j++) {
      if (ZW_PicGroup.children[i].children[j].tag == 'img') {

        if (ZW_PicGroup.children[i].children[j].parent.tag == 'tag0') {
          console.log(ZW_PicGroup.children[i].children[j].parent);
        }
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;
        collistionArray.push(tmpBox);
        //console.log(ZW_PicGroup.children[i].children[j].parent.tag);
        //console.log(ZW_PicGroup.children[i].children[j]);
        tagArray.push(ZW_PicGroup.children[i].children[j].parent.tag);
      }
      if (ZW_PicGroup.children[i].children[j].tag == 'i1') {
        //console.log('i1');
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;

        tmpPointArray.push(tmpBox[0]);
        tmpPointArray.push(tmpBox[1]);
        // var tmpArray = [tmpBox[0]];
        // tmpArray.push();
        pArray1.push(tmpBox[0]);
        pArray1.push(tmpBox[1]);
        //console.log(tmpBox);
      }
      if (ZW_PicGroup.children[i].children[j].tag == 'i2') {
        //console.log('i2');
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;

        tmpPointArray.push(tmpBox[0]);
        tmpPointArray.push(tmpBox[1]);

        pArray2.push(tmpBox[0]);
        pArray2.push(tmpBox[1]);
        // console.log(tmpBox);
      }
      if (ZW_PicGroup.children[i].children[j].tag == 'i3') {
        //console.log('i3');
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;

        tmpPointArray.push(tmpBox[0]);
        tmpPointArray.push(tmpBox[1]);

        pArray3.push(tmpBox[0]);
        pArray3.push(tmpBox[1]);
      }
      if (ZW_PicGroup.children[i].children[j].tag == 'i4') {
        //console.log('i4');
        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;

        tmpPointArray.push(tmpBox[0]);
        tmpPointArray.push(tmpBox[1]);

        pArray4.push(tmpBox[0]);
        pArray4.push(tmpBox[1]);
      }

      if (ZW_PicGroup.children[i].children[j].tag == 'img1') {

        var tmpBox = ZW_PicGroup.children[i].children[j].AABB;
        for (var k = 0; k < ZW_PicGroup.children[i].children.length; k++) {
          if (ZW_PicGroup.children[i].children[k].tag == 'text') {
            //console.log(ZW_PicGroup.children[i].children[k].text);
            var RespMemo = ZW_PicGroup.children[i].children[k].text;   //定义字符串

            var re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则
            var re1 = /[a-z]/g;  //小写字母
            var re2 = /[A-Z]/g;  //大写字母
            //console.log(RespMemo.match(re1));
            var leng = RespMemo.match(re) ? RespMemo.match(re).length : 0;  //计算中文的个数
            var leng1 = RespMemo.match(re1) ? RespMemo.match(re).length : 0;  //计算小写字母的个数
            var leng2 = RespMemo.match(re2) ? RespMemo.match(re).length : 0;  //计算大写字母的个数

            // console.log(leng);
            // console.log(leng1);
            // console.log(leng2);

            var wordWidth = leng * 20 + leng1 * 10 + leng2 * 15;
            //console.log(tmpBox);
            tmpBox[0] = tmpBox[0] + tmpBox[2] * 0.5 - wordWidth * 0.5;
            tmpBox[2] = wordWidth;
            //console.log(tmpBox);
          }

        }
        collistionArray.push(tmpBox);
        tagArray.push(ZW_PicGroup.children[i].children[j].parent.tag);

        tmpPointArray.push(tmpBox[0]);
        tmpPointArray.push(tmpBox[1]);

        tmpPointArray.push(tmpBox[0] + tmpBox[2]);
        tmpPointArray.push(tmpBox[1]);

        tmpPointArray.push(tmpBox[0]);
        tmpPointArray.push(tmpBox[1] + tmpBox[3]);

        tmpPointArray.push(tmpBox[0] + tmpBox[2]);
        tmpPointArray.push(tmpBox[1] + tmpBox[3]);
      }

    }

    collistionArray1.push(tmpPointArray);
  }
  // console.log(pArray1);
  // console.log(pArray2);
  // console.log(pArray3);
  // console.log(pArray4);
  console.log(collistionArray);
  console.log(tagArray);
  console.log(collistionArray1);

  // var bInter = JudgeIntersect(199,79,199,207,169,179+29,280,179+29);
  // if(bInter){
  //   console.log('相交')
  // }else
  // {
  //   console.log('不相交')
  // }

  var bColl = false;
  for (var i = 0; i < collistionArray1.length; i++) {
    var p1X_0 = collistionArray1[i][0];
    var p1Y_0 = collistionArray1[i][1];
    var p2X_0 = collistionArray1[i][2];
    var p2Y_0 = collistionArray1[i][3];
    var p3X_0 = collistionArray1[i][4];
    var p3Y_0 = collistionArray1[i][5];
    var p4X_0 = collistionArray1[i][6];
    var p4Y_0 = collistionArray1[i][7];

    for (var j = 0; j < collistionArray1.length; j++) {
      if (i != j) {
        var p1X_1 = collistionArray1[j][0];
        var p1Y_1 = collistionArray1[j][1];
        var p2X_1 = collistionArray1[j][2];
        var p2Y_1 = collistionArray1[j][3];
        var p3X_1 = collistionArray1[j][4];
        var p3Y_1 = collistionArray1[j][5];
        var p4X_1 = collistionArray1[j][6];
        var p4Y_1 = collistionArray1[j][7];

        var bColl1 = JudgeIntersect(p1X_0, p1Y_0, p2X_0, p2Y_0, p1X_1, p1Y_1, p2X_1, p2Y_1);
        var bColl2 = JudgeIntersect(p1X_0, p1Y_0, p2X_0, p2Y_0, p1X_1, p1Y_1, p3X_1, p3Y_1);
        var bColl3 = JudgeIntersect(p1X_0, p1Y_0, p2X_0, p2Y_0, p3X_1, p3Y_1, p4X_1, p4Y_1);
        var bColl4 = JudgeIntersect(p1X_0, p1Y_0, p2X_0, p2Y_0, p2X_1, p2Y_1, p4X_1, p4Y_1);

        var bColl5 = JudgeIntersect(p1X_0, p1Y_0, p3X_0, p3Y_0, p1X_1, p1Y_1, p2X_1, p2Y_1);
        var bColl6 = JudgeIntersect(p1X_0, p1Y_0, p3X_0, p3Y_0, p1X_1, p1Y_1, p3X_1, p3Y_1);
        var bColl7 = JudgeIntersect(p1X_0, p1Y_0, p3X_0, p3Y_0, p3X_1, p3Y_1, p4X_1, p4Y_1);
        var bColl8 = JudgeIntersect(p1X_0, p1Y_0, p3X_0, p3Y_0, p2X_1, p2Y_1, p4X_1, p4Y_1);

        var bColl9 = JudgeIntersect(p3X_0, p3Y_0, p4X_0, p4Y_0, p1X_1, p1Y_1, p2X_1, p2Y_1);
        var bColl10 = JudgeIntersect(p3X_0, p3Y_0, p4X_0, p4Y_0, p1X_1, p1Y_1, p3X_1, p3Y_1);
        var bColl11 = JudgeIntersect(p3X_0, p3Y_0, p4X_0, p4Y_0, p3X_1, p3Y_1, p4X_1, p4Y_1);
        var bColl12 = JudgeIntersect(p3X_0, p3Y_0, p4X_0, p4Y_0, p2X_1, p2Y_1, p4X_1, p4Y_1);

        var bColl13 = JudgeIntersect(p2X_0, p2Y_0, p4X_0, p4Y_0, p1X_1, p1Y_1, p2X_1, p2Y_1);
        var bColl14 = JudgeIntersect(p2X_0, p2Y_0, p4X_0, p4Y_0, p1X_1, p1Y_1, p3X_1, p3Y_1);
        var bColl15 = JudgeIntersect(p2X_0, p2Y_0, p4X_0, p4Y_0, p3X_1, p3Y_1, p4X_1, p4Y_1);
        var bColl16 = JudgeIntersect(p2X_0, p2Y_0, p4X_0, p4Y_0, p2X_1, p2Y_1, p4X_1, p4Y_1);

        bColl = bColl1 || bColl2 || bColl3 || bColl4 || bColl5 || bColl6 || bColl7 || bColl8 || bColl9 || bColl10 || bColl11 || bColl12 || bColl13 || bColl14 || bColl15 || bColl16;

        if (bColl) {
          SetSelectPic('');
          SetSelectPic0(tagArray[i]);
          SetSelectPic0(tagArray[j]);
          return [bColl, tagArray[i], tagArray[j]];
        }

        console.log(i);
      }
    }
  }
  return [bColl];


  var bColl = false;
  for (var i = 0; i < collistionArray.length; i++) {
    var BoxMinX1 = collistionArray[i][0];
    var BoxMinY1 = collistionArray[i][1];
    var BoxMaxX1 = collistionArray[i][0] + collistionArray[i][2];
    var BoxMaxY1 = collistionArray[i][1] + collistionArray[i][3];

    for (var j = 0; j < collistionArray.length; j++) {
      if (i != j) {
        var BoxMinX2 = collistionArray[j][0];
        var BoxMinY2 = collistionArray[j][1];
        var BoxMaxX2 = collistionArray[j][0] + collistionArray[j][2];
        var BoxMaxY2 = collistionArray[j][1] + collistionArray[j][3];


        //console.log(collistionArray);
        bColl = BoxMaxX1 < BoxMinX2 || BoxMinX1 > BoxMaxX2 || BoxMaxY1 < BoxMinY2 || BoxMinY1 > BoxMaxY2 ? false : true;
        if (bColl) {
          SetSelectPic('');
          SetSelectPic0(tagArray[i]);
          SetSelectPic0(tagArray[j]);
          return [bColl, tagArray[i], tagArray[j]];
        }
      }
    }
  }

  return [bColl];
}


//获取图片位置
function GetPicPosition(tag) {
  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    if (ZW_PicGroup.children[i].tag == tag) {
      return [ZW_PicGroup.children[i].x, ZW_PicGroup.children[i].y];
    }
  }
}

//保存图片（不包含背景）
function SaveImage2() {

  that.ctx.toDataURL({
    x: 0,
    y: 0,
    width: that.ctx.width,
    height: that.ctx.height,
  }).then(dataURL => {
    console.log(dataURL);
    that.setData({
        webGLOffset: 0
      });
      if (ZW_Platform == 'Android') {
        UpdateCup(dataURL);
      }else
      {
        ProcessTexture('map_Default',dataURL,'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/map_normal.png');
      }
      
      //UpdateCup(dataURL);
  });
  return;


  ZW_BackImg.visible = false; //隐藏背景图片 
  that.ctx.clearRect(0, 0, ZW_Width, ZW_Height);
  that.stage.update();

  //截图并获取base64
  // that.ctx.toDataURL({
  //   x: 0, 
  //   y: 0,
  //   width: that.ctx.width,
  //   height: that.ctx.height,
  // }).then(dataURL => {
  //   console.log(dataURL);
  //   ZW_BackImg.visible = true; //隐藏背景图片 
  //    
  // });

  //图片路径
  that.ctx.toTempFilePath({
    success(res) {
      // console.log(res);
      ctx0.clearRect(0, 0, ZW_Width, ZW_Height);
      ctx0.drawImage(res.apFilePath, 1010 * 0.5 - 0.5 * (638 - 26) * that.data.cardWidth / that.data.cardHeight, 13, (638 - 26) * that.data.cardWidth / that.data.cardHeight, 638 - 26)
      ctx0.draw();
      var tim = setTimeout(function () {
        ctx0.toDataURL({
          x: 0,
          y: 0,
          width: ctx0.width,
          height: ctx0.height,
        }).then(dataURL => {
          console.log(dataURL);
          that.ctx.clearRect(0, 0, ZW_Width, ZW_Height);
          that.stage.update();
        });
        clearTimeout(tim);
      }, 100);

      ZW_BackImg.visible = true; //隐藏背景图片 

    },
  });
}

//保存图片（包含背景）
function SaveImage1() {
  
  //return;
  // ctx0.toDataURL({
  //   x: 0,
  //   y: 0,
  //   width: ctx0.width,
  //   height: ctx0.height,
  // }).then(dataURL => {
  //   console.log(dataURL);

  // });
  // return;

  //截图并获取base64

  that.ctx.toDataURL({
    x: 0,
    y: 0,
    width: that.ctx.width,
    height: that.ctx.height,
  }).then(dataURL => {
    console.log(dataURL);
    that.setData({
        webGLOffset: 0
      });
      if (ZW_Platform == 'Android') {
        UpdateCup('http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/testpng1.png');
      }else
      {
        ProcessTexture('map_Default','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/testpng1.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/map_normal.png');
      }
      //ProcessTexture('map_Default','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/testpng1.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/map_normal.png');
      //UpdateCup('http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/testpng.png?t=1');
  });
  return;

  console.log(that.data.cardWidth)

  that.stage.update();

  //图片路径
  that.ctx.toTempFilePath({
    success(res) {
      ctx0.clearRect(0, 0, ZW_Width, ZW_Height);
      ctx0.drawImage(res.apFilePath, 1010 * 0.5 - 0.5 * (638 - 26) * that.data.cardWidth / that.data.cardHeight, 13, (638 - 26) * that.data.cardWidth / that.data.cardHeight, 638 - 26)
      ctx0.draw();
      var tim = setTimeout(function () {
        ctx0.toDataURL({
          x: 0,
          y: 0,
          width: ctx0.width,
          height: ctx0.height,
        }).then(dataURL => {
          console.log(dataURL);
          //console.log(dataURL.length);
          if (dataURL.length < 30000) {
            SaveImage1();
          } else {
            //SaveImage2();
          }

        });
        clearTimeout(tim);
      }, 100);
    },
  });
}

function initContentAreas() {
  // g_contentAreasGroup
  var areas = g_selectedSceneData.contentAreaList;
  for (var i = 0; i < areas.length; i++) {
    let areaData = areas[i];
    let areaBoundGroup = new cax.Group();

    areaBoundGroup.tag = areaData.contentAreaId;

    let gridList = areaData.areaIndexList;
    let startPosIndex = areaData.initPosIndex;

    let startPosXIndex = startPosIndex % 10;
    let startPosYIndex = Math.floor(startPosIndex / 10);

    let startPosX = startPosIndex % 10 * g_gridWidth;
    let startPosY = Math.floor(startPosIndex / 10) * g_gridWidth;

    let contentHeightNum = areaData.areaHeight;
    let contentWidthNum = areaData.areaWidth;

    for (var j = 0; j < gridList.length; j++) {
      let gridindex = gridList[j];

      // 横位置
      let gridXIndex = gridindex % 10;
      // 纵位置
      let gridYIndex = Math.floor(gridindex / 10);
      // 网格中的位置
      let parentIndexX = startPosXIndex + gridXIndex;
      let parentIndexY = startPosYIndex + gridYIndex;

      // left
      if (gridXIndex == 0 || gridList.indexOf(gridindex - 1) == -1)
        addBorderLine(j, g_gridWidth * parentIndexX, g_gridWidth * parentIndexY + g_elementPadding, 1, g_gridWidth - 2 * g_elementPadding, areaBoundGroup,
          areaData.borderColor);

      // top
      if (gridYIndex == 0 || gridList.indexOf(gridindex - 10) == -1)
        addBorderLine(j, g_gridWidth * parentIndexX + g_elementPadding, g_gridWidth * parentIndexY, g_gridWidth - + g_elementPadding * 2, 1, areaBoundGroup,
          areaData.borderColor);

      // right
      if (gridList.indexOf(gridindex + 1) == -1)
        addBorderLine(j, g_gridWidth * (parentIndexX + 1), g_gridWidth * parentIndexY + g_elementPadding, 1, g_gridWidth - g_elementPadding * 2, areaBoundGroup,
          areaData.borderColor);

      // bottom
      if (gridList.indexOf(gridindex + 10) == -1)
        addBorderLine(j, g_gridWidth * (parentIndexX + 0) + g_elementPadding, g_gridWidth * (parentIndexY + 1), g_gridWidth - g_elementPadding * 2, 1, areaBoundGroup,
          areaData.borderColor);
    }

    g_contentAreasGroup.add(areaBoundGroup)
  }

}

function initBackGroundGrid() {
  g_hGridNum = sceneData.widthGridNum;
  g_vGridNum = sceneData.heightGridNum;
  g_gridWidth = Math.floor(Math.min(that.data.cardWidth / g_hGridNum, that.data.cardHeight / g_vGridNum));

  let hGridNum = sceneData.widthGridNum;
  let vGridNum = sceneData.heightGridNum;
  console.log("initBackGroundGrid : " + hGridNum + ' - ' + vGridNum + ' - ' + g_gridWidth);


  // var bgGroup = new cax.Group();
  // bgGroup.alpha = 1.0
  // bgGroup.x = 0 + that.data.cardWidth / 2;
  // bgGroup.y = 0 + that.data.cardHeight / 2;
  // bgGroup.originX = 0 + that.data.cardWidth / 2;
  // bgGroup.originY = 0 + that.data.cardHeight / 2;

  // bgGroup.tag = "bg-group";
  // const img = new cax.Bitmap(g_selectedContentAreaData.backgroundImg, null, that.data.cardWidth, that.data.cardHeight);
  // img.x = 0;
  // img.y = 0;
  // img.rect = [0, 0, that.data.cardWidth, that.data.cardHeight];
  // img.tag = 'img';

  // bgGroup.add(img);


  var x = 0;
  var y = 0;
  var width = 500;
  var height = 200;
  var url = g_selectedSceneData.backgroundImg;

  // AddPic("bg-img", 0, 0, width, height, url);
  // var picGroup = new cax.Group();
  // picGroup.alpha = 1.0
  // picGroup.x = x + width / 2;
  // picGroup.y = y + height / 2;
  // picGroup.originX = x + width / 2;
  // picGroup.originY = y + height / 2;

  // picGroup.tag = "bg-group";
  // const img = new cax.Bitmap(url, null, width, height);
  // img.x = x;
  // img.y = y;
  // img.rect = [0, 0, width, height];
  // img.tag = 'bg-img';

  // picGroup.add(img);



  // g_gridGroup.add(picGroup);

  // console.log("initBackGroundGrid bg :" + bg.width + ' - ' + bg.height)


  for (var i = 0; i < hGridNum - 1; i++) {
    var rect = new cax.Rect(1, g_gridWidth * vGridNum, {
      lineWidth: 0.5,
      strokeStyle: "#0A603F55",
      setLineDash: [5, 15],
    });

    rect.x = 0 + g_gridWidth * (i + 1);
    rect.y = 0;
    rect.tag = 'grid-h-' + i;
    g_gridGroup.add(rect);
  }

  for (var i = 0; i < vGridNum - 1; i++) {
    var rect = new cax.Rect(g_gridWidth * vGridNum, 1, {
      lineWidth: 0.5,
      strokeStyle: "#0A603F55",
      setLineDash: [5, 15],
    });

    rect.x = 0;
    rect.y = 0 + g_gridWidth * (i + 1);
    rect.tag = 'grid-v-' + i;
    g_gridGroup.add(rect);
  }

  addBorderLine(0, 0, 0, g_gridWidth * vGridNum, 1, g_gridBorderGroup);
  addBorderLine(1, g_gridWidth * hGridNum, 0, 1, g_gridWidth * vGridNum, g_gridBorderGroup);
  addBorderLine(2, 0, g_gridWidth * vGridNum, g_gridWidth * vGridNum, 1, g_gridBorderGroup);
  addBorderLine(3, 0, 0, 1, g_gridWidth * vGridNum, g_gridBorderGroup);
  ShowProcess();
}

var addBorderLine = function (index, posX, posY, hWidth, vWidth, parent, strokeColor = "#0A603F", fillColor = '#ffffff00') {
  var rect = new cax.Rect(hWidth, vWidth, {
    lineWidth: 1,
    strokeStyle: strokeColor,
    fillStyle: fillColor,
    setLineDash: [5, 15],
  });

  rect.x = posX;
  rect.y = posY;
  rect.tag = 'grid-border-' + index;
  parent.add(rect);
}

//场景初始化
function InitScene(inst, url1, url2) {
  console.log(inst);
  const stage = new cax.Stage(100, 100, 'myCanvas', inst, "taobao");
  const group = new cax.Group();
  g_gridGroup = new cax.Group();
  g_gridBorderGroup = new cax.Group();
  ZW_PicGroup = new cax.Group();
  g_contentAreasGroup = new cax.Group();

  group.add(g_gridBorderGroup);
  group.add(g_gridGroup);
  group.add(ZW_PicGroup);
  group.add(g_contentAreasGroup);

  ZW_BackImg = new cax.Bitmap(url1, null, 0, 0)
  ZW_BackImg.x = 0;
  ZW_BackImg.rect = [0, 0, inst.data.cardWidth, inst.data.cardHeight];
  ZW_BackImg.compositeOperation = 'destination-over'; //目标图形和源图形内容后面的目标图形会被绘制
  stage.add(group);

  inst.stage = stage;
  ZW_BackImg.on('touchStart', () => {
    console.log('back');
  });

  initBackGroundGrid();
  initContentAreas();

  ShowProcess()
}


function CanvasDraw() {
  // if(ZW_Need_Update)
  // {
  //   //console.log('ss');
  //   that.ctx.clearRect(0,0,ZW_Width,ZW_Height);
  //   that.stage.update();
  //   ZW_Need_Update = false;
  // } 
  // console.log('ss');
  that.ctx.clearRect(0, 0, ZW_Width, ZW_Height);
  that.stage.update();


  //that.ctx.getContext('2d').requestAnimationFrame(draw);

  //stats.end();
  //canvas.requestAnimationFrame(draw);
}

//设置滑块位置
function SetSliderValue(value) {
  if (!value) value = 0;
  //var sliderWidth = ZW_Width0-160;
  that.setData({
    sliderLeft: 80 - 11 + (ZW_Width0 - 160) * (value + 180.0) / 360.0
  });
}

//通过滑块位置计算角度
function GetSliderRotValue(value) {
  if (!value) value = windowWidth / 2 - 11;


  return -180 + 360.0 * (value - (80 - 11)) / (ZW_Width0 - 160)
  //var sliderWidth = ZW_Width0-160;
  // that.setData({
  //     sliderLeft: 80-11+ (ZW_Width0-160)*(value + 180.0)/360.0
  //   });
}

Page({
  data: {
    sliderLeft: 169,
    sliderValue: 0,
    cardLeft: 80,  //卡片的左偏移
    cardTop: 130, //卡片的上偏移
    cardWidth: 410,  //卡片的左偏移
    cardHeight: 260, //卡片的上偏移
    debugStr: "debug-str",
    webGLOffset:1000
  }, 
  onLoad(query) {
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
  },
  onReady() {
    // 页面加载完成
    var res = my.getSystemInfoSync();
    var { windowWidth, windowHeight, pixelRatio, } = res;
    this.setData({
      windowWidth,
      windowHeight,
      pixelRatio,

    }, () => {
      that = this;

      this.setData({
        sliderLeft: windowWidth / 2 - 11
      });

      //方形卡初始化数据-------------
      this.setData({    //设置卡片宽高
        cardWidth: 410,
        cardHeight: 260
      });
      var url1 = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/card.png';  //卡片图片
      var url2 = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/cardmask.png';  //卡片蒙版图片
      //方形卡初始化数据-------------

      //心型卡初始化数据-------------
      this.setData({    //设置卡片宽高
        cardWidth: 540,
        cardHeight: 540*1.5,
      });
      var url1 = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/heartback.png';  //卡片图片
      var url2 = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/heartmask.png';  //卡片蒙版图片
      //心形卡初始化数据-------------


      //         this.setData({ //设置卡片宽高
      // cardWidth: 600,
      // cardHeight:380
      // });
      // var url1 = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pattern/1d3d92a4-27f3-4e0f-bd9c-f655923597db.png'; //卡片图片
      // var url2 = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pattern/df724984-004e-4c20-a34f-e058759c12a7.png'; //卡片蒙版图片
      //console.log(windowWidth-this.data.cardWidth*0.5);


      this.setData({  //设置卡片canvas在场景中偏移
        cardLeft: windowWidth * 0.5 - this.data.cardWidth * 0.25,
        cardTop: windowHeight * 0.5 - this.cardHeight * 0.5
      });

      ZW_Width = windowWidth * pixelRatio;
      ZW_Height = windowHeight * pixelRatio;

      ZW_PixelRatio = pixelRatio;

      ZW_Width0 = windowWidth;

      console.log("ZW_Width = " + ZW_Width)
      console.log("ZW_Height = " + ZW_Height)

      that.ctx = my.createCanvasContext('canvas', { "enableNative": true });
      ctx0 = my.createCanvasContext('canvas0', { "enableNative": true });

      //this.interval = setInterval(CanvasDraw.bind(this), 60);
      //CanvasDraw(this);

      //that.ctx.imageSmoothingEnabled = true;
      // console.log(that.ctx);
      //that.ctx.width = ZW_Width*3;
      InitScene(that, url1, url2);

      // AddPic('tag0', 100, 80, 411, 328, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/cup.png');
      // AddPic('tag1', 220, 220, 370, 1780, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/test0.jpg');
      //AddPic0('tag-rect', 100, 120, 192, 120, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/starbucks/rect.png');
      // AddText('tag0', 106, 170, 180, 30, '你AB你');

      Rect_Data = [100, 120, 192, 120];//虚线框数据
      Text_Data = [106, 170, 180, 30];//文字框数据
    });

  },
  canvasStart: function (event) {
    //SetSliderValue(180);
    //SaveImage0();  
    //console.log(event); 
    // RemovePic('tag0');
    //  
    //that.stage.update();
    //console.log(ZW_PixelRatio); 

    if (event.touches && event.touches[0]) {
      event.changedTouches[0].x = event.changedTouches[0].x * 2;
      event.changedTouches[0].y = event.changedTouches[0].y * 2;
      // this.stage.scaleX = 2;
      // this.stage.scaleY = 2;
      this.stage.touchStartHandler(event);
      //console.log(Drag_Type);

      Last_Pos = [event.changedTouches[0].x, event.changedTouches[0].y];
      //console.log(e.type, e.touches[0].x, e.touches[0].y);

      if (Drag_Type == '') SetSelectPic('');




    }
    // if (e.touches && e.touches[0]) {
    //   e.touches[0].x = e.touches[0].x / 3 * 8;
    //   e.touches[0].y = e.touches[0].y / 3 * 8;
    //   //console.log(e.type, e.touches[0].x, e.touches[0].y);
    // } else {
    //   //console.log(e.type);
    // }
  },

  canvasMove: function (event) {
    if (event.touches && event.touches[0]) {
      event.changedTouches[0].x = event.changedTouches[0].x * 2;
      event.changedTouches[0].y = event.changedTouches[0].y * 2;

      var Current_Pos = [event.changedTouches[0].x, event.changedTouches[0].y];
      var offsetX = Current_Pos[0] - Last_Pos[0];
      var offsetY = Current_Pos[1] - Last_Pos[1];

      that.addDebugStr("Current_Pos:" + Current_Pos[0] + " " + Current_Pos[1]);
      that.addDebugStr("Last_Pos:" + Last_Pos[0] + " " + Last_Pos[1]);

      if (CurrentPicTag == '')
        return;

      var myPos = GetPicPosition(CurrentPicTag);


      let reBorder = checkIsHitBorder(CurrentPicTag, myPos[0] + offsetX, myPos[1] + offsetY);
      let reOther = checkIsElementHitOther(CurrentPicTag, myPos[0] + offsetX, myPos[1] + offsetY);

      let addOffsetX = (reBorder[0] && reOther[1]) == 1 ? offsetX : 0;
      let addOffsetY = (reBorder[1] && reOther[1]) == 1 ? offsetY : 0;

      // addOffsetX = offsetX;
      // addOffsetY = offsetY;

      if (Drag_Type == 'pic') {
        SetPicPosition(CurrentPicTag, myPos[0] + addOffsetX, myPos[1] + addOffsetY);

      }

      Last_Pos = Current_Pos;
    }
  },

  canvasMoveBak: function (event) {
    if (event.touches && event.touches[0]) {
      event.changedTouches[0].x = event.changedTouches[0].x * 2;
      event.changedTouches[0].y = event.changedTouches[0].y * 2;

      var Current_Pos = [event.changedTouches[0].x, event.changedTouches[0].y];
      var offsetX = Current_Pos[0] - Last_Pos[0];
      var offsetY = Current_Pos[1] - Last_Pos[1];
      //console.log(offsetX+','+offsetY);
      if (CurrentPicTag != '') {
        var myPos = GetPicPosition(CurrentPicTag);
        if (Drag_Type == 'pic') {

          if (GetPicType(CurrentPicTag) == 'text' && ZW_Text_Control) {

            if (myPos[1] + offsetY > Rect_Data[1] + Text_Data[3] / 2 && myPos[1] + offsetY < Rect_Data[1] + Rect_Data[3] - Text_Data[3] / 2 - 2)
              SetPicPosition(CurrentPicTag, myPos[0], myPos[1] + offsetY);
          } else {
            SetPicPosition(CurrentPicTag, myPos[0] + offsetX, myPos[1] + offsetY);
          }

        } else if (Drag_Type == 'scale') {
          var currentScale = GetPicScale(CurrentPicTag);
          if (offsetX < 0) {
            if (currentScale > 1.5) {
              console.log('太大了');
              return;
            }
            SetPicScale(CurrentPicTag, currentScale * 1.01);
          } else {
            if (currentScale < 0.7) {
              console.log('太小了');
              return;
            }
            SetPicScale(CurrentPicTag, currentScale * 0.99);
          }
        }

      }
      Last_Pos = Current_Pos;

    }
  },
  canvasEnd: function (event) {
    if (CurrentPicTag && Drag_Type)
      movePicAfter(CurrentPicTag);
    Drag_Type = null;
  },

  canvasStart1: function (event) {
    var tmpTag = GetClickedTag(event);

    if(tmpTag == 'closeBtn')
    {
      //canvas.width /=3;
      that.setData({
        webGLOffset: 1000
      });

      return;
    }

    switch (event.touches.length) {

      case 1:
        _state = STATE.TOUCH_ROTATE;
        

        _moveCurr.copy(getMouseOnCircle(event.touches[0].x, event.touches[0].y));
        _movePrev.copy(_moveCurr);
        break;
      case 2:
        
        break;
      default:
        _state = STATE.TOUCH_PAN;
        var x = (event.touches[0].x + event.touches[1].x) / 2;
        var y = (event.touches[0].y + event.touches[1].y) / 2;
        _panStart.copy(getMouseOnScreen(x, y));
        _panEnd.copy(_panStart);
        break;
    }
    
    //console.log(event);
  },
  canvasMove1: function (event) {
    switch (event.touches.length) {
      case 1:
        if (_state === STATE.TOUCH_ROTATE) {
          showTime = (new Date()).getTime();

          HideOrShowTab(false);
          TabState = false;
          
          _movePrev.copy(_moveCurr);
          _moveCurr.copy(getMouseOnCircle(event.touches[0].x, event.touches[0].y));
        }
        //console.log(_moveCurr);
        break;
      default:
        showTime = (new Date()).getTime();
        
        HideOrShowTab(false);
        TabState = false;

        _state = STATE.TOUCH_ZOOM_PAN;
        var dx = event.touches[0].x - event.touches[1].x;
        var dy = event.touches[0].y - event.touches[1].y;

        if (_touchZoomDistanceStart < 1.001 && _touchZoomDistanceStart > 0.999 && _touchZoomDistanceEnd < 1.001 && _touchZoomDistanceEnd > 0.999) {
          _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy);
        } else {
          _touchZoomDistanceEnd = parseInt(Math.sqrt(dx * dx + dy * dy));
        }

        break;
    }
  },
  canvasEnd1: function (event) {
    switch (event.touches.length) {
      case 0:
        _state = STATE.NONE;
        _touchZoomDistanceEnd = _touchZoomDistanceStart = 1;
        break;
      default:
        _state = STATE.NONE;
        _moveCurr.copy(getMouseOnCircle(event.touches[0].x, event.touches[0].y));
        _movePrev.copy(_moveCurr);
        _panStart.copy(_panEnd);
        break;
    }
  },

  sliderStart: function (event) {

    var tmpValue = event.touches[0].pageX;
    if (tmpValue > 80 - 11 - 1 && tmpValue < ZW_Width0 - 80 - 11 + 1) {
      this.setData({
        sliderLeft: tmpValue
      });

      var rotValue = GetSliderRotValue(tmpValue);
      if (CurrentPicTag != '')
        SetPicRotation(CurrentPicTag, rotValue);
      //console.log(rotValue);
    }
    //console.log(StartSliderValue);
  },
  sliderMove: function (event) {

    var tmpValue = event.touches[0].pageX;
    if (tmpValue > 80 - 11 - 1 && tmpValue < ZW_Width0 - 80 - 11 + 1) {
      this.setData({
        sliderLeft: tmpValue
      });

      var rotValue = GetSliderRotValue(tmpValue);
      if (CurrentPicTag != '')
        SetPicRotation(CurrentPicTag, rotValue);
      //console.log(rotValue);
    }

    //console.log(tmpValue - (ZW_Width0/2-11));
    // that.sliderLeft += tmpValue-StartSliderValue;
    // console.log(that.sliderLeft);
    //StartSliderValue = tmpValue;
    //  += tmpValue-StartSliderValue;
  },
  sliderEnd: function (event) {
    StartSliderValue = 0;
  },
  saveImg1() {  //截图1
    //SetSelectPic('');
    var tim = setTimeout(function () {
      SaveImage1();
      clearTimeout(tim);
    }, 100);
  },
  saveImg2() {  //截图2 
    SaveImage2();
  },

  collisionDetection() {  //碰撞检测 
    var bCol = CollisionDetection();
    console.log(bCol);
    if (bCol.length > 1) {
      console.log('碰撞了,碰撞tag为' + bCol[1] + ',' + bCol[2]);
    } else {
      console.log('没碰撞！！！');
    }
  },
  updateText() {  //修改文字 
    // UpdateText('tag0', '测试的美好的');
    // AddText('tag2', 110, 220, 170, 30, '测试的美好的祝福'); 
    UpdateText('starPink-text-0', ['测试的美好的2324', '测试fdsfdfd的美好的fsdafasdf']);

  },
  addPic() {  //添加图片 
    // AddPic('tag1', 200, 80, 111, 128, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pattern/8f466b67-52ef-4732-a06b-659484d6de68.png');

    //AddPic('tag2', 170, 180, 111, 128, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pattern/catAndDog.png');
    //SetPicVisible('tag-rect',true);

    let addAreaIndex = checkIsHaveEnoughGapInAreaBeforeCreate(g_selectedSceneData.contentAreaList[1].contentAreaId , 
      g_selectedSceneData.candidateImagesList[5].imageGridList);

    if(addAreaIndex != -1) {
      addPicFromExternal(g_selectedSceneData.contentAreaList[1].contentAreaId,
        "starPink2-pic-" + t_picSum++, g_selectedSceneData.candidateImagesList[5].imageUrl,
        g_selectedSceneData.candidateImagesList[5].imageGridHSum,
        g_selectedSceneData.candidateImagesList[5].imageGridVSum,
        g_selectedSceneData.candidateImagesList[5].imageGridHSum,
        g_selectedSceneData.candidateImagesList[5].imageGridVSum,
        g_selectedSceneData.candidateImagesList[5].imageGridList,
        g_selectedSceneData.candidateImagesList[5].imageGridList,
        addAreaIndex,
        g_selectedSceneData.candidateImagesList[5].imageOrignWidth,
        g_selectedSceneData.candidateImagesList[5].imageOrignHeight);
    } else {
      my.alert({content:"加个p哦！位置不够啦！"});
    }

    // addTextFromExternal("StarBucksCustomized2-area-3", "starPink-text-" + t_textSum++,
    //   ["吃个egg 吃个p 吃个蛋蛋fsafasdfasdffsafasdfsa"], [0.9, 0, 0.5, 0]);

  },
  changeText() {  //切换文字状态 
    ZW_Text_Control = false;
    RemovePic('tag-rect');
    //SetPicVisible('tag-rect',false);

  },
  onShow() {
    // 页面显示
    if(Screen_Width > 0) return;
    var res = my.getSystemInfoSync();
    const { windowWidth, windowHeight } = res;
    this.setData({
      windowWidth,
      windowHeight
    }, () => {
      // LoadGlbModel('https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/test1.zb');
      // // //LoadGlbModel0('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/5.glb');
      // return;
      ZW_Platform = my.getSystemInfoSync().platform;
      ZW_PixelRatio = my.getSystemInfoSync().pixelRatio;
      my._createCanvas({
        id: 'canvasGL',
        success: (c) => {
          var webgl = c.getContext('webgl');

          canvas = c;
          gl = webgl;
          // ZW_PixelRatio = 2;
          // canvas.width *= ZW_PixelRatio;
          // canvas.height *= ZW_PixelRatio;

          if (ZW_Platform == 'Android') {
            var info = my.getSystemInfoSync();

            canvas.width *= ZW_PixelRatio;
            canvas.height *= ZW_PixelRatio;
            ZW_Width1 = canvas.width;
            ZW_Height1 = canvas.height;

            // this.setData({
            //   bottomValue: 2.0
            // });

          } else {
            // var info = my.getSystemInfoSync();
            // this.setData({
            //   topOffset: info.titleBarHeight+info.statusBarHeight
            // });

            var windowSize = GetWindowSize();
            ZW_Height1 = windowSize[1] * ZW_PixelRatio;
            ZW_Width1 = windowSize[0] * ZW_PixelRatio;

            canvas.width = ZW_Width1;
            canvas.height = ZW_Height1;
          }

          Screen_Width = ZW_Width1;
          
          InitScene1();

          //AddImage('back', 0, 0, windowWidth, 1624*windowWidth/750, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/back0.png', 10);
        }
      });
    });
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },

  addDebugStr(str) {
    let tempStr = "\r\n" + str;
    tempStr += this.data.debugStr;
    this.setData({
      debugStr: tempStr,
    })
  }
});

function getContentAreaById(inId) {
  for (var i = 0; i < g_selectedSceneData.contentAreaList.length; i++) {
    if (g_selectedSceneData.contentAreaList[i].contentAreaId == inId)
      return g_selectedSceneData.contentAreaList[i];
  }
  return null;
}

/**
 * 从外部加入图片
 * @param {*} areaId 加入的区域id
 * @param {*} inTag 加入的图片tag
 * @param {*} inUrl 图片url
 * @param {*} picWidthGridSum 图片格子宽度
 * @param {*} picHeightGridSum 图片骨子高度
 * @param {*} orignPicWidthGridSum 图片格子原始高度  可能缩放
 * @param {*} orignPicHeightGridSum 图片格子原始高度  可能缩放
 * @param {*} picGridList 图片自身的占位list
 * @param {*} orignPicGridList 图片原始自身的占位list 可能缩放
 * @param {*} startInAreaIndex 在区域中的位置序号
 * @param {*} originWidth 图片原始宽度
 * @param {*} originHeight 图片原始高度

 */
function addPicFromExternal(areaId, inTag, inUrl, picWidthGridSum, picHeightGridSum, orignPicWidthGridSum,
  orignPicHeightGridSum, picGridList, orignPicGridList,
  startInAreaIndex, originWidth, originHeight) {
  // debugger
  // 图片实际宽高
  var picWidth = picWidthGridSum * g_gridWidth;
  var picHeight = picHeightGridSum * g_gridWidth;

  // 所处区域Data
  let areaData = getContentAreaById(areaId);

  // pic在区域内起始位置的横纵分量
  let startInAreaXIndex = startInAreaIndex % 10;
  let startInAreaYIndex = Math.floor(startInAreaIndex / 10);

  // 区域在网格中起始位置的横纵分量
  let startAreaInGridXIndex = areaData.initPosIndex % 10;
  let startAreaInGridYIndex = Math.floor(areaData.initPosIndex / 10);

  // pic在网格中的位置index
  let startPosIndex = (startAreaInGridYIndex + startInAreaYIndex) * 10 + (startAreaInGridXIndex + startInAreaXIndex);

  // pic在网格中的位置横纵分量
  let startPosXIndex = startPosIndex % 10;
  let startPosYIndex = Math.floor(startPosIndex / 10);

  // pic在网格中的起始位置坐标
  let startPosX = startPosIndex % 10 * g_gridWidth;
  let startPosY = Math.floor(startPosIndex / 10) * g_gridWidth;

  // 图片根节点
  var picGroup = new cax.Group();
  picGroup.alpha = 1.0
  picGroup.x = startPosX;
  picGroup.y = startPosY;
  picGroup.originX = startPosX;
  picGroup.originY = startPosY;

  // 图片
  picGroup.tag = inTag;
  picGroup.tAreaId = areaId;
  picGroup.tOrignPicGridList = orignPicGridList;
  picGroup.tPicGridList = picGridList;
  picGroup.tStartInAreaIndex = startInAreaIndex;
  picGroup.tUrl = inUrl;


  picGroup.currentScaleX = picWidthGridSum;
  picGroup.currentScaleY = picHeightGridSum;
  picGroup.initScaleX = orignPicWidthGridSum;
  picGroup.initScaleY = orignPicHeightGridSum;
  picGroup.tOriginWidth = originWidth;
  picGroup.tOriginHeight = originHeight;

  // 图片
  const img = new cax.Bitmap(inUrl, null, picWidth, picHeight, () => {
    ShowProcess();
  });
  img.x = startPosX;
  img.y = startPosY;
  img.currentScaleX = picWidthGridSum;
  img.currentScaleY = picHeightGridSum;
  img.initScaleX = orignPicWidthGridSum;
  img.initScaleY = orignPicHeightGridSum;
  // img.

  img.rect = [0, 0, originWidth, originHeight];
  img.tag = 'img';
  picGroup.add(img);

  img.scaleX = picWidth / originWidth;
  img.scaleY = picHeight / originHeight;

  ZW_PicGroup.add(picGroup);

  // 包围盒group
  var picBoundGroup = new cax.Group();
  picBoundGroup.tag = "bounds";
  for (var j = 0; j < picGridList.length; j++) {
    let gridindex = picGridList[j];

    // 横位置
    let gridXIndex = gridindex % 10;
    // 纵位置
    let gridYIndex = Math.floor(gridindex / 10);
    // 网格中的位置
    let parentIndexX = startPosXIndex + gridXIndex;
    let parentIndexY = startPosYIndex + gridYIndex;

    // left
    if (gridXIndex == 0 || picGridList.indexOf(gridindex - 1) == -1)
      addBorderLine(j, g_gridWidth * parentIndexX + g_elementPadding,
        g_gridWidth * parentIndexY + g_elementPadding, 1, g_gridWidth - g_elementPadding * 2, picBoundGroup,
        "#555555");

    // top
    if (gridYIndex == 0 || picGridList.indexOf(gridindex - 10) == -1)
      addBorderLine(j, g_gridWidth * parentIndexX + g_elementPadding,
        g_gridWidth * parentIndexY + g_elementPadding, g_gridWidth - g_elementPadding * 2, 1, picBoundGroup,
        "#555555");

    // right
    if (picGridList.indexOf(gridindex + 1) == -1)
      addBorderLine(j, g_gridWidth * (parentIndexX + 1) - g_elementPadding,
        g_gridWidth * parentIndexY + g_elementPadding, 1, g_gridWidth - g_elementPadding * 2, picBoundGroup,
        "#555555");

    // bottom
    if (picGridList.indexOf(gridindex + 10) == -1)
      addBorderLine(j, g_gridWidth * (parentIndexX + 0) + g_elementPadding,
        g_gridWidth * (parentIndexY + 1) - g_elementPadding, g_gridWidth - g_elementPadding * 2, 1, picBoundGroup,
        "#555555");
  }

  img.on('touchStart', () => {
    //console.log(img);
    SetSelectPic(inTag);
    CurrentPicTag = inTag;
    Drag_Type = 'pic';
  });

  picGroup.add(picBoundGroup);

  let rPosIndex = picGridList[0];
  // 横位置
  let rPosXIndex = rPosIndex % 10;
  // 纵位置
  let rPosYIndex = Math.floor(rPosIndex / 10);
  // 网格中的位置
  let parentIndexX = startPosXIndex + rPosXIndex;
  let parentIndexY = startPosYIndex + rPosYIndex;

  let parentPosX = (startPosXIndex + rPosXIndex) * g_gridWidth;
  let parentPosY = (startPosYIndex + rPosYIndex) * g_gridWidth;

  var rImg = new cax.Bitmap('/img/remove.png', () => {
    // debugger
    ShowProcess();
  }, 24, 24);
  rImg.x = parentPosX - 0;
  rImg.y = parentPosY - 0;
  rImg.rect = [0, 0, 24, 24];
  rImg.tag = 'remove';
  rImg.scaleX = 1.5;
  rImg.scaleY = 1.5;
  picGroup.add(rImg);

  rImg.on('touchStart', () => {
    RemovePic(inTag);
    SetSliderValue(0);
  });
  that.addDebugStr("add ok")
  ShowProcess();

  // scale start
  let lastPosIndex = picGridList[picGridList.length - 1];
  // 横位置
  let lastPosXIndex = lastPosIndex % 10;
  // 纵位置
  let lastPosYIndex = Math.floor(lastPosIndex / 10);
  // 网格中的位置
  let sIndexX = startPosXIndex + lastPosXIndex;
  let sIndexY = startPosYIndex + lastPosYIndex;

  let sPosX = (sIndexX + 0.9) * g_gridWidth;
  let sPosY = (sIndexY + 0.9) * g_gridWidth;


  const sImg = new cax.Bitmap('/img/scale.png', () => {
    // debugger
    ShowProcess();
  }, 24, 24);
  sImg.x = sPosX - 25;
  sImg.y = sPosY - 25;
  sImg.rect = [0, 0, 24, 24];
  sImg.scaleX = 1.5;
  sImg.scaleY = 1.5;
  sImg.tag = 'scale';
  picGroup.add(sImg);

  sImg.on('touchStart', (event) => {
    console.log("img scale tag = " + picGroup.tag)

    let selectAreaId = areaId;
    let currentScaleX = picGroup.currentScaleX;
    let currentScaleY = picGroup.currentScaleY;
    let initScaleX = picGroup.initScaleX;
    let initScaleY = picGroup.initScaleY;

    let tempScaleX = currentScaleX + 1;
    let tempScaleY = currentScaleY + 1;
    let currentAreaIndex = picGroup.tStartInAreaIndex;

    let tempPicGridList = [];
    for (var i = 0; i < tempScaleY; i++) {
      for (var j = 0; j < tempScaleX; j++) {
        tempPicGridList.push((i * 10) + j);
      }
    }

    let re = checkIsHaveEnoughGapInAreaPos(selectAreaId, currentAreaIndex, tempPicGridList, picGroup.tag);

    if (re == -1) {
      if (initScaleX == currentScaleX && initScaleY == currentScaleY)
        my.alert({ content: "瞎啊，没地方给你放大了！" });
      else {
        addPicFromExternal(selectAreaId, "starPink2-pic-" + t_picSum++, picGroup.tUrl,
          initScaleX, initScaleY, initScaleX, initScaleY, picGroup.tOrignPicGridList, picGroup.tOrignPicGridList,
          currentAreaIndex, picGroup.tOriginWidth, picGroup.tOriginHeight);
        RemovePic(picGroup.tag);

      }
    } else {
      addPicFromExternal(selectAreaId, "starPink2-pic-" + t_picSum++, picGroup.tUrl,
        tempScaleX, tempScaleY, initScaleX, initScaleY, tempPicGridList, picGroup.tOrignPicGridList,
        currentAreaIndex, picGroup.tOriginWidth, picGroup.tOriginHeight);
      RemovePic(picGroup.tag);
    }


    console.log("img scale re = " + re)
  });


  // scale end

}

/**
 * 从外部加入文字
 * @param {*} areaId 加入的区域id
 * @param {*} inTag 加入的图片tag
 * @param {*} inTextList 加入的文字（可能多行）
 * @param {*} textPaddingRatioList padding 格子宽度的比例值 0.5半个格子 1整个格子
 *  左上右下
 */
function addTextFromExternal(areaId, inTag, inTextList, textPaddingRatioList) {
  // 所处区域Data
  let areaData = getContentAreaById(areaId);

  // 区域在网格中起始位置的横纵分量
  let startAreaInGridXIndex = areaData.initPosIndex % 10;
  let startAreaInGridYIndex = Math.floor(areaData.initPosIndex / 10);

  let areaWidthSum = areaData.areaWidth;
  let areaHeightSum = areaData.areaHeight;

  let startPosX = startAreaInGridXIndex * g_gridWidth;
  let startPosY = startAreaInGridYIndex * g_gridWidth;
  let areaWidth = areaData.areaWidth * g_gridWidth;
  let areaHeight = areaData.areaHeight * g_gridWidth;


  let textStartPosX = (startAreaInGridXIndex) * g_gridWidth;
  let textStartPosY = (startAreaInGridYIndex) * g_gridWidth;

  let textEndPosX = (startAreaInGridXIndex + areaWidthSum) * g_gridWidth;
  let textEndPosY = (startAreaInGridYIndex + areaHeightSum) * g_gridWidth;

  var picGroup = new cax.Group();
  picGroup.alpha = 1.0
  picGroup.x = startPosX;
  picGroup.y = startPosY;
  picGroup.originX = startPosX;
  picGroup.originY = startPosY;

  picGroup.tag = inTag;
  const img = new cax.Bitmap('/img/touming.png', null, areaWidth, areaHeight);
  img.x = startPosX;
  img.y = startPosY;
  img.rect = [0, 0, areaWidth, areaHeight];
  img.tag = 'text-bg';

  picGroup.add(img);

  var picTextGroup = new cax.Group();
  picTextGroup.tag = inTag;

  for (var i = 0; i < inTextList.length; i++) {
    let defaultTextSize = g_gridWidth / 2;
    const img1 = new cax.Text(inTextList[i], {
      font: Math.floor(defaultTextSize / inTextList.length) + "px" + ' Arial',
      color: '#000000',
      // maxWidth: Math.abs(textEndPosX - textStartPosX) - (textPaddingRatioList[0] * 2 * g_gridWidth ),
      baseline: 'middle',
      textAlign: 'center',
      maxWidth: 200

    });
    img1.x = textStartPosX + areaWidth / 2;
    img1.y = textStartPosY + (areaHeight / (inTextList.length * 2)) * ((i * 2) + 1);
    // img1.width = 200;
    // img1.rect = [0, 0, 200, 200];
    img1.width = Math.abs(textEndPosX - textStartPosX - (textPaddingRatioList[0] * 2 * g_gridWidth));
    img1.height = Math.abs(textStartPosY - textEndPosY) - (textPaddingRatioList[1] * 2 * g_gridWidth);
    img1.rect = [0 + textPaddingRatioList[0] * g_gridWidth, 0 + textPaddingRatioList[1] * g_gridWidth,
    areaWidth - (textPaddingRatioList[0] + textPaddingRatioList[2]) * g_gridWidth, areaHeight - (textPaddingRatioList[1] + textPaddingRatioList[3]) * g_gridWidth];
    img1.tag = 'text-content-' + i;

    let paddingLeft = textPaddingRatioList[0] * g_gridWidth;
    let paddingRight = textPaddingRatioList[2] * g_gridWidth;
    let paddingTop = textPaddingRatioList[1] * g_gridWidth;
    let paddingBottom = textPaddingRatioList[3] * g_gridWidth;

    let clipWidth = Math.abs(textEndPosX - textStartPosX) - paddingLeft - paddingRight;
    let clipHeight = Math.abs(textEndPosX - textStartPosX) - paddingTop - paddingBottom;

    const clipPath = new cax.Graphics()
      .beginPath()
      .closePath()
      .fillStyle('#f4862c55')
      .fill()
      .strokeStyle('black')
      .stroke()
    // clipPath.x = startPosX + textPaddingRatioList[0] * g_gridWidth;
    // clipPath.y = startPosY + textPaddingRatioList[1] * g_gridWidth;
    clipPath.rect(0 - (areaWidth / 2) + paddingLeft, 0 - (areaHeight / 2) + paddingTop, clipWidth, clipHeight);

    // clipPath.arc(0, 0, 150, 150, Math.PI * 2)
    // clipPath.rect(0, 0, areaWidth / 2, areaHeight / 2)

    img1.clip(clipPath)
    picTextGroup.add(img1);

    let graphics = new cax.Graphics()
    graphics
      .beginPath()
      // .arc(0, 0, 10, 0, Math.PI * 2)
      .rect(-135 * 1.5, -135 * 0.5, 135 * 3, 135)
      .closePath()
      .fillStyle('#f4862c55')
      .fill()
      .strokeStyle('black')
      .stroke()

    graphics.x = 0;
    graphics.y = 0;

    ShowProcess()

    // debugger
  }

  ZW_PicGroup.add(picTextGroup);

  // 包围盒group
  var picBoundGroup = new cax.Group();
  picBoundGroup.tag = "bounds";
  let picGridList = areaData.areaIndexList;
  for (var j = 0; j < picGridList.length; j++) {
    let gridindex = picGridList[j];

    // 横位置
    let gridXIndex = gridindex % 10;
    // 纵位置
    let gridYIndex = Math.floor(gridindex / 10);
    // 网格中的位置
    let parentIndexX = startAreaInGridXIndex + gridXIndex;
    let parentIndexY = startAreaInGridYIndex + gridYIndex;

    // left
    if (gridXIndex == 0 || picGridList.indexOf(gridindex - 1) == -1)
      addBorderLine(j, g_gridWidth * parentIndexX + g_elementPadding,
        g_gridWidth * parentIndexY + g_elementPadding, 1, g_gridWidth - g_elementPadding * 2, picBoundGroup,
        "#555555");

    // top
    if (gridYIndex == 0 || picGridList.indexOf(gridindex - 10) == -1)
      addBorderLine(j, g_gridWidth * parentIndexX + g_elementPadding,
        g_gridWidth * parentIndexY + g_elementPadding, g_gridWidth - g_elementPadding * 2, 1, picBoundGroup,
        "#555555");

    // right
    if (picGridList.indexOf(gridindex + 1) == -1)
      addBorderLine(j, g_gridWidth * (parentIndexX + 1) - g_elementPadding,
        g_gridWidth * parentIndexY + g_elementPadding, 1, g_gridWidth - g_elementPadding * 2, picBoundGroup,
        "#555555");

    // bottom
    if (picGridList.indexOf(gridindex + 10) == -1)
      addBorderLine(j, g_gridWidth * (parentIndexX + 0) + g_elementPadding,
        g_gridWidth * (parentIndexY + 1) - g_elementPadding, g_gridWidth - g_elementPadding * 2, 1, picBoundGroup,
        "#555555");
  }

  picGroup.add(picBoundGroup);

  that.addDebugStr("add ok")
  ShowProcess();
}

function movePicAfter(inTag) {
  let selectPic = getPicElement(inTag);
  let selectPicPosX = selectPic.x;
  let selectPicPosY = selectPic.y;
  // debugger

  let areaId = selectPic.tAreaId

  // let areaData = getContentAreaById(areaId);
  let areaData = getContentAreaById(areaId);

  // 区域在网格中的起始位置
  let startPosIndex = areaData.initPosIndex;
  let startPosXIndex = startPosIndex % 10;
  let startPosYIndex = Math.floor(startPosIndex / 10);

  let startPosX = startPosIndex % 10 * g_gridWidth;
  let startPosY = Math.floor(startPosIndex / 10) * g_gridWidth;

  let minDis = Number.MAX_VALUE;
  let nearestGridIndex = 0;

  for (var i = 0; i < g_vGridNum; i++) {
    for (var j = 0; j < g_hGridNum; j++) {

      let gridIndexX = j;
      let gridIndexY = i;
      let gridIndex = gridIndexX + gridIndexY * 10;

      let gridPosX = gridIndexX * g_gridWidth;
      let gridPosY = gridIndexY * g_gridWidth;

      let distance = Math.pow((gridPosX - selectPicPosX), 2) + Math.pow((gridPosY - selectPicPosY), 2);

      if (distance < minDis) {
        nearestGridIndex = gridIndex;
        minDis = distance;
      }
    }
  }

  console.log("movePicAfter nearestAreaIndex = " + nearestGridIndex);

  if (checkIsHaveEnoughGapInArea(nearestGridIndex, areaData, selectPic.tPicGridList)) {
    // nearestGridIndex 最近的网格 需要转换为区域内的序号

    selectPic.tStartInAreaIndex = nearestGridIndex - startPosIndex;
    SetPicPosition(inTag, nearestGridIndex % 10 * g_gridWidth, Math.floor(nearestGridIndex / 10) * g_gridWidth);
  } else {
    SetPicPosition(inTag, (startPosIndex + selectPic.tStartInAreaIndex) % 10 * g_gridWidth, 
      Math.floor((startPosIndex + selectPic.tStartInAreaIndex) / 10) * g_gridWidth);
  }
}

function checkIsHaveEnoughGapInArea(nearestGridIndex, areaData, picGridList) {
  // debugger
  let areaInitPosIndex = areaData.initPosIndex;

  let startGapInGridIndex = nearestGridIndex - areaInitPosIndex;

  let startGapInGridIndexX = startGapInGridIndex % 10;
  let startGapInGridIndexY = Math.floor(startGapInGridIndex / 10);

  for (var i = 0; i < picGridList.length; i++) {
    let picGridItemPosIndex = picGridList[i];
    let toPosIndex = startGapInGridIndex + picGridItemPosIndex;

    if (areaData.areaIndexList.indexOf(toPosIndex) < 0)
      return false;
  }

  return true;
}

function checkIsHaveEnoughGapInAreaPos(areaId, areaIndex, picGridList, exceptPicTag = '') {
  let areaData = getContentAreaById(areaId);
  let areaIndexList = areaData.areaIndexList;

  // 图片以areaIndex为起点 在区域内的占位list
  let picGridListInArea = [];
  let isAreaHaveGap = true;
  for (var j = 0; j < picGridList.length; j++) {
    picGridListInArea.push(picGridList[j] + areaIndex);
    if (areaIndexList.indexOf(picGridList[j] + areaIndex) < 0) {
      isAreaHaveGap = false;
      break;
    }
  }

  if (isAreaHaveGap == false) {
    return -1;
  }

  let isHaveSet = false;
  for (var m = 0; m < ZW_PicGroup.children.length; m++) {
    let targetPic = ZW_PicGroup.children[m];

    if (targetPic.tAreaId != areaData.contentAreaId || targetPic.tag == exceptPicTag)
      continue;

    let startPosIndex = targetPic.tStartInAreaIndex;

    let isHave = false;
    for (var n = 0; n < targetPic.tPicGridList.length; n++) {
      let haveSet = picGridListInArea.indexOf(targetPic.tPicGridList[n] + startPosIndex)
      if (haveSet >= 0) {
        isHave = true;
        break;
      }
    }

    if (isHave) {
      isHaveSet = true;
      break
    }
  }

  if (isHaveSet)
    return -1;
  else
    return areaIndex;
}


/**
 * 遍历区域网格中的一个格子为起点，判断是否可以放下输入的网格序列 
 * @param {*} areaData 
 * @param {*} picGridList 
 */
function checkIsHaveEnoughGapInAreaBeforeCreate(areaId, picGridList) {
  // let areaInitPosIndex = areaData.initPosIndex;
  let areaData = getContentAreaById(areaId);
  let areaIndexList = areaData.areaIndexList;

  let re = -1;
  for (var i = 0; i < areaIndexList.length; i++) {
    // 遍历区域内的每个index  以index为起点 检查可以放入新的indexlist
    let areaIndex = areaIndexList[i];
    let re = checkIsHaveEnoughGapInAreaPos(areaId, areaIndex, picGridList);
    if (re == -1) {
      continue;
    } else {
      return areaIndex;
    }

    // 图片以areaIndex为起点 在区域内的占位list
    // let picGridListInArea = [];
    // let isAreaHaveGap = true;
    // for (var j = 0; j < picGridList.length; j++) {
    //   picGridListInArea.push(picGridList[j] + areaIndex);
    //   if (areaIndexList.indexOf(picGridList[j] + areaIndex) < 0) {
    //     isAreaHaveGap = false;
    //     break;
    //   }
    // }

    // if (isAreaHaveGap == false) {
    //   continue;
    // }

    // let isHaveSet = false;
    // for (var m = 0; m < ZW_PicGroup.children.length; m++) {
    //   let targetPic = ZW_PicGroup.children[m];

    //   if (targetPic.tAreaId != areaData.contentAreaId)
    //     continue;

    //   let startPosIndex = targetPic.tStartInAreaIndex;

    //   let isHave = false;
    //   for (var n = 0; n < targetPic.tPicGridList.length; n++) {
    //     let haveSet = picGridListInArea.indexOf(targetPic.tPicGridList[n] + startPosIndex)
    //     if (haveSet >= 0) {
    //       isHave = true;
    //       break;
    //     }
    //   }

    //   if (isHave) {
    //     isHaveSet = true;
    //     break
    //   }
    // }

    // if (isHaveSet)
    //   continue;

    // else
    //   return areaIndex;
  }

  return -1;
}

/**
 * 
 */
function checkIsElementHitOther(inPicTag, inOffsetX, inOffsetY) {
  let re = [1, 1];
  let selectPic = getPicElement(inPicTag);
  let areaId = selectPic.tAreaId
  let inAreaData = getContentAreaById(areaId);

  let selectPicCurrentPosX = inOffsetX;
  let selectPicCurrentPosY = inOffsetY;
  let gapX = inOffsetX - selectPic.x;
  let gapY = inOffsetY - selectPic.y;

  // 图片的网格indexs
  let selectPicIndexs = selectPic.tPicGridList;

  // 图片在区域中的起始index
  let selectPicStartInAreaIndex = selectPic.tStartInAreaIndex;
  let selectPicStartInAreaIndexX = selectPicStartInAreaIndex % 10;
  let selectPicStartInAreaIndexY = Math.floor(selectPicStartInAreaIndex / 10);

  let selectBoundLines = [];
  let selectBoundsGroup = getElementFromParent(selectPic, "bounds");

  for (var i = 0; i < selectBoundsGroup.children.length; i++) {
    // 包围盒item的包围线
    let tempbound = selectBoundsGroup.children[i];

    let tmpBox = tempbound.AABB;
    let point0X = tmpBox[0] + gapX;
    let point0Y = tmpBox[1] + gapY;

    let isH = tmpBox[2] > 1 ? true : false;
    let point1X = tmpBox[2] > 1 ? (tmpBox[0] + tmpBox[2]) : tmpBox[0];
    let point1Y = tmpBox[3] > 1 ? (tmpBox[1] + tmpBox[3]) : tmpBox[1];

    point1X += gapX;
    point1Y += gapY;

    selectBoundLines.push({ point0X, point0Y, point1X, point1Y, isH })
  }

  for (var i = 0; i < ZW_PicGroup.children.length; i++) {
    let targetPic = ZW_PicGroup.children[i];

    if (targetPic.tAreaId != areaId || targetPic.tag == inPicTag)
      continue;

    let targetBoundsGroup = getElementFromParent(targetPic, "bounds");
    let targetBoundLines = [];
    for (var j = 0; j < targetBoundsGroup.children.length; j++) {
      let tempTbound = targetBoundsGroup.children[j];
      let tmpTBox = tempTbound.AABB;
      let pointT0X = tmpTBox[0];
      let pointT0Y = tmpTBox[1];

      let isTH = tmpTBox[2] > 1 ? true : false;
      let pointT1X = tmpTBox[2] > 1 ? (tmpTBox[0] + tmpTBox[2]) : tmpTBox[0];
      let pointT1Y = tmpTBox[3] > 1 ? (tmpTBox[1] + tmpTBox[3]) : tmpTBox[1];

      targetBoundLines.push({ pointT0X, pointT0Y, pointT1X, pointT1Y, isTH })
    }

    re = isLinesHitLines(selectBoundLines, targetBoundLines);
    return re;
  }
  return re;
}

function isLinesHitLines(inAlines, inBlines) {
  let re = [1, 1];
  for (var i = 0; i < inAlines.length; i++) {
    for (var j = 0; j < inBlines.length; j++) {
      let aData = inAlines[i];
      let bData = inBlines[j];
      // if (aData.isH != bData.isTH)
      //   continue;

      let isX = JudgeIntersect(
        aData.point0X, aData.point0Y, aData.point1X, aData.point1Y,
        bData.pointT0X, bData.pointT0Y, bData.pointT1X, bData.pointT1Y);
      // console.log("isX = " + isX)
      if (isX) {
        re[0] = 0;
        re[1] = 0;
        return re;
      }
    }
  }
  return re;
}
/**
 * @param {*} inPicTag 选中的picTag
 * @param {*} inOffsetX 鼠标位置x
 * @param {*} inOffsetY 鼠标位置y
 * @param {*} inAreaData 区域数据
 * @param {*} picGridList 图片网格数组
 * 
 * return [0,0]  x、y方向
 */
function checkIsHitBorder(inPicTag, inOffsetX, inOffsetY) {
  let re = [1, 1];
  that.stage.updateAABB();

  let selectPic = getPicElement(inPicTag);

  let areaId = selectPic.tAreaId

  // let areaData = getContentAreaById(areaId);
  let inAreaData = getContentAreaById(areaId);


  let selectPicCurrentPosX = inOffsetX;
  let selectPicCurrentPosY = inOffsetY;

  let gapX = inOffsetX - selectPic.x;
  let gapY = inOffsetY - selectPic.y;


  // 图片的网格indexs
  let selectPicIndexs = selectPic.tPicGridList;

  // 图片在区域中的起始index
  let selectPicStartInAreaIndex = selectPic.tStartInAreaIndex;
  let selectPicStartInAreaIndexX = selectPicStartInAreaIndex % 10;
  let selectPicStartInAreaIndexY = Math.floor(selectPicStartInAreaIndex / 10);


  // area在网格中的起始位置index 
  let areaStartPosInGridIndex = inAreaData.initPosIndex;
  let areaStartPosInGridIndexX = areaStartPosInGridIndex % 10;
  let areaStartPosInGridIndexY = Math.floor(areaStartPosInGridIndex / 10);

  let boundsGroup = getElementFromParent(selectPic, "bounds");

  for (var m = 0; m < boundsGroup.children.length; m++) {
    // 包围盒item的包围线
    let tempbound = boundsGroup.children[m];

    let tmpBox = tempbound.AABB;

    let point0X = tmpBox[0] + gapX;
    let point0Y = tmpBox[1] + gapY;

    let isH = tmpBox[2] > 1 ? true : false;
    let point1X = tmpBox[2] > 1 ? (tmpBox[0] + tmpBox[2]) : tmpBox[0];
    let point1Y = tmpBox[3] > 1 ? (tmpBox[1] + tmpBox[3]) : tmpBox[1];

    point1X += gapX;
    point1Y += gapY;

    let areaBoundsGroup = getElementFromParent(g_contentAreasGroup, inAreaData.contentAreaId);
    for (var n = 0; n < areaBoundsGroup.children.length; n++) {
      let areaBound = areaBoundsGroup.children[n];
      let tmpAreaBox = areaBound.AABB;
      let areaBoundPoint0 = [tmpAreaBox[0], tmpAreaBox[1]];
      let areaBoundPoint1 = [tmpAreaBox[0] + tmpAreaBox[2], tmpAreaBox[1] + tmpAreaBox[3]];
      let isAreaBoundH = tmpAreaBox[2] > 1 ? true : false;

      // let isX = JudgeIntersect(
      //   point0X, point0Y, point1X, point1Y,
      //   areaBoundPoint0[0], areaBoundPoint0[1], areaBoundPoint1[0], areaBoundPoint1[1]);

      let isX = JudgeIntersect(
        point0X, point0Y, point1X, point1Y,
        areaBoundPoint0[0], areaBoundPoint0[1], areaBoundPoint1[0], areaBoundPoint1[1]);
      // console.log("isX = " + isX)
      if (isX) {
        re[0] = 0;
        re[1] = 0;
        return re;
      }
    }
  }
  return re;
}

//3d场景初始化
function InitScene1() {
  ZW_Scene = new THREE.Scene()
  //ZW_Camera = new THREE.PerspectiveCamera(20, canvas.width / canvas.height, 1, 100000);
  ZW_Renderer = new THREE.WebGLRenderer({precision: 'highp', antialias: true, canvas: canvas, context: gl, alpha: true })

  ZW_raycaster = new THREE.Raycaster();

  ZW_normalCamera = new THREE.PerspectiveCamera(45, canvas.width / canvas.height, 0.01, 100000); //常规视角相机
  //var json = JSON.parse( '{"dd":"Line","url": "lineline"}' );

  // my.alert({
  //       content: haha,
  //       buttonText: '好',
  //       success: () => {

  //       },
  //     });

  var geometry = new THREE.Geometry();
  var material = new THREE.MeshBasicMaterial({
    color: 0xff0000
  });

  ZW_SceneParent = new THREE.Mesh(geometry, material);
  ZW_Scene.add(ZW_SceneParent);

  ZW_SelectParent = new THREE.Mesh(geometry, material);
  if(ZW_Platform == 'Android'){

  }else
  {
    // var info = my.getSystemInfoSync();
    // my.alert({content:info});
    var windowSize = GetWindowSize();
    // if(windowSize[1] < 800)
    // ZW_SelectParent.position.x += 100000;
  }
  ZW_SelectParent.visible = true;
  ZW_SceneParent.add(ZW_SelectParent);

  ZW_CenterNode0 = new THREE.Mesh(geometry);
  ZW_SceneParent.add(ZW_CenterNode0);


  ZW_CenterNode = new THREE.Mesh(geometry);
  ZW_CenterNode0.add(ZW_CenterNode);

  

  ZW_CameraNode = new THREE.Mesh(geometry);
  ZW_CenterNode.add(ZW_CameraNode);

        var lightValue = 1.2;
        if (ZW_Platform == 'Anroid') {
          lightValue = 0.2;
        }
        // var light = new THREE.AmbientLight( 0xffffff );
        // light.intensity = 5;
        // ZW_SceneParent.add(light);
        // var light2 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light2.position.set(0, 0, 1); 
        // light2.name = 'main_light';
        // ZW_SceneParent.add(light2);

        //light 1
        // var light0 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light0.position.set(0, 1, 1); 
        // light0.name = 'main_light';
        // ZW_SceneParent.add(light0);

        // var light1 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light1.position.set(0, -1, -1); 
        // light1.name = 'main_light';
        // ZW_SceneParent.add(light1);

        // //light2
        // var light2 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light2.position.set(1, 1, 0); 
        // light2.name = 'main_light';
        // ZW_SceneParent.add(light2);

        // var light3 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light3.position.set(-1, -1, 0); 
        // light3.name = 'main_light';
        // ZW_SceneParent.add(light3);

        //light3
//         var light = new THREE.HemisphereLight( 0xffffbb, 0xffffff, 2 );
// ZW_SceneParent.add( light );

         var light1 = new THREE.DirectionalLight(0xffffff, lightValue*1.0);
        light1.position.set(0, -1, 0); 
        light1.name = 'main_light';
        ZW_SceneParent.add(light1);

        // var light2 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light2.position.set(0, 0, 1); 
        // light2.name = 'main_light';
        // ZW_SceneParent.add(light2);

         

        // var light3 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light3.position.set(0, 0, -1); 
        // light3.name = 'main_light';
        // ZW_SceneParent.add(light3);

        // var light4 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light4.position.set(0, 0, -1); // ~60º
        // light4.name = 'main_light';
        // ZW_SceneParent.add(light4);

        // var light5 = new THREE.DirectionalLight(0xffffff, lightValue);
        // light5.position.set(0, 0, 1); // ~60º
        // light5.name = 'main_light';
        // ZW_SceneParent.add(light5);

        
        ZW_Renderer.toneMappingExposure = 2.8;  //light add
        ZW_Renderer.physicallyCorrectLights = true;
        // ZW_Renderer.gammaOutput = true;
        // ZW_Renderer.gammaFactor = 2;

  //SetBackColor(16, 16, 16, 1.0);
  SetBackColor(16, 16, 16, 0.0);
  animate();

  // AddBack('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/back0.png');

  //ZW_SelectParent.visible = false;

  var backPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/back1.png?t=1';
  //AddImage('back', 679 * 1350, 1388 * 1500, backPath, 30000, -60000, 140000, 0);

  var tipsPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/tips.png?t=1';
  var tipsMaskPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/tips-mask.png?t=1';
  //AddImage3('tips', 679 * 1300, 388 * 1300, tipsPath, tipsMaskPath ,0, -169 + 220000, 19 - 200000, 1.0 ,0,10);

  

  // var handPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/hand.png';
  // AddImage4('hand', 80 * 1300, 82 * 1300, handPath, 80000, 200000, 450000-10000-180000, 1.0 ,0,12);

  // StartPositionAnimation('hand', [80000, 200000, 450000-10000-180000], [80000, 200000, 450000-10000], 2000,0,10000);
  // SetVisibleByTag('hand',false);
  

  // var text1Path = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/pic/hhxm.png';
  // AddImage('text1', 128 * 1400, 40 * 1400, text1Path, 475000-170000, 200000, 450000+430000, 11);
  
  //HideUI();

  //SetVisibleByTag('tips',true);
  //SwitchScene(0);
 //InitUI();

  ZW_FinishSceneBox = new THREE.Box3(new THREE.Vector3(-314003.6654, -136173.8249, -227644.276724), new THREE.Vector3(370205.6857, 139004.08459, 299282.62518));

  var mysize = new THREE.Vector3();
  ZW_FinishSceneBox.getSize(mysize);
  ZW_SceneSize = mysize.length();
  ResetViewPort();

  // setInterval(function(){ 
  //   ZW_ProcessValue += 0.01;
  //   OnProcess(ZW_ProcessValue);
  // }, 300);

  
  showTime = (new Date()).getTime();
  timestamp = (new Date()).getTime();

  // var coords = {x:0};
  // new TWEEN.Tween(coords) 
  //       .to({ x: 1.0}, 10000)
  //       .repeat(0)
  //       .easing(TWEEN.Easing.Quadratic.InOut) 
  //       .onUpdate(function() { 
  //           ZW_ProcessValue = coords.x;
  //          OnProcess(ZW_ProcessValue);
  //       })
  //       .delay(0)
  //       .start(); 

  //LoadGlbModel('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/2020.10.29/GLB/AJ6-notexture.glb');

  LoadGlbModel('http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/cup-notexture.glb');
  

  //LoadGlbModel('http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/bag/bag.glb');
  //LoadGlbModel('/img/AJ6-notexture.glb');

 

}

function HideUI(){
  
} 

function InitUI(){
  var maskPath1 = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/mask.png?t=1';
  AddImage4('mask1', 750 * 1900, 453 * 1900, maskPath1, 30000, 200000, -490000, 1.0 ,0,0);

  if (ZW_Platform == 'Android') {
  } else {
    var maskPath = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/mask.png?t=1';
    AddImage4('mask', 750 * 1900, 453 * 1900, maskPath, 30000, 200000, -490000, 1.0, 0, 0);
  }
   

  var shadowPath = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/shadow.png?t=1';
  AddImage4('shadow', 214 * 1500, 78 * 1500, shadowPath, 25000-3000, 200000, -340000, 1.0 ,0,0);

  var logoPath = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/logo.png?t=1';
  AddImage1('logo', 277 * 1500, 67 * 1500, logoPath, 30000, 200000, 760000+80000, 1.0 ,0,0);

   var tipsPath = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/360.png?t=1';
  AddImage1('tips', 121 * 1500, 121 * 1500, tipsPath, 360000+20000, 200000, 460000, 1.0 ,0,0);

  var text1Path = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/text0.png?t=1';
  AddImage1('text1', 313 * 1500, 74 * 1500, text1Path, 30000, 200000, -450000, 1.0 ,0,-1);

  var closeBtnPath = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/btn0.png?t=1';
  AddImage1('closeBtn', 275 * 1500, 69 * 1500, closeBtnPath, 30000, 200000, -680000, 1.0 ,0,-1);

  // var logoPath1 = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/preview/logo.png?t=1';
  // AddImage1('logo1', 277 * 1, 67 * 1, logoPath1, 30000, 200000, 760000+80000, 1.0 ,0,3);
}


function SwitchShoe(index1) {
  // var rotArray = [[1.4402,7.04317,0.3331546],[1.08685,5.95976,-0.31261],[1.87223,7.3375,0.33315]];
  // var scaleArray = [[1806.29,1806.29,1806.29],[1854.918,1854.918,1854.918],[2473.7816,2473.7816,2473.7816]];

  var rotArray = [[1.4402,7.04317,0.3331546],[1.05485,5.20776,-0.31261],[1.87223,7.3375,0.33315]];
  var scaleArray = [[1806.29,1806.29,1806.29],[2064.784656,2064.784656,2064.784656],[2473.7816,2473.7816,2473.7816]];

  var shoeNode = ZW_SceneParent.getObjectByName('ZW_33');
  StartRotationAnimation('ZW_33', [shoeNode.rotation.x, shoeNode.rotation.y, shoeNode.rotation.z], [rotArray[index1][0],rotArray[index1][1],rotArray[index1][2]], 500);
  StartScaleAnimation('ZW_33', [shoeNode.scale.x, shoeNode.scale.y, shoeNode.scale.z], [scaleArray[index1][0],scaleArray[index1][1],scaleArray[index1][2]], 500);
}

//切换分类
function SwitchScene(index1){
  
}

function SetVisibleByTag(tag,visible)
{
  ZW_SceneParent.getObjectByName(tag).visible = visible;
}


function SetAlphaByTag(tag,alpha)
{
  ZW_SceneParent.getObjectByName(tag).material.uniforms.alpha.value = alpha;
  // ZW_SceneParent.getObjectByName(tag).material.uniforms.alpha.needsUpdate = true;
  // ZW_SceneParent.getObjectByName(tag).material.needsUpdate = true;
  // ShowProcess();
}

function SetColorByTag(tag,red,green,blue)
{
  ZW_SceneParent.getObjectByName(tag).material.uniforms.color.value = new THREE.Vector3(red/255.0, green/255.0, blue/255.0);;
}

function AddShadow0() {
  var picPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/aj-shadow.png';
  //  var imgTex1 = new THREE.TextureLoader().load(canvas, 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/AJ6/'+nodeName +'_normal.png');
    
  //   imgTex1.wrapS = imgTex1.wrapT = 1000;
  //   imgTex1.minFilter = THREE.NearestFilter;
  //   imgTex1.needsUpdate = true;
  //   myobj.children[0].material.normalMap = imgTex1;

    var sprite =new THREE.TextureLoader().load(canvas, picPath);

    //var planeGeometry = new THREE.PlaneGeometry(4200, 30000 );
    var planeGeometry = new THREE.PlaneGeometry(701669, 271230);
    var planeMaterial = new THREE.MeshBasicMaterial();
    var plane = new THREE.Mesh(planeGeometry, planeMaterial);
    //plane.rotation.z = Math.PI;
    // plane.position.x = 0.22;
    // plane.position.y = -0.06;
  plane.position.x = 16969.100881836;
  plane.position.y = -23519.797397460497;
  plane.position.z = -165326.507694922 - 1000;

    //plane.position.z = -500;
    plane.material.transparent = true;
    plane.material.map = sprite;
    plane.material.map.needsUpdate = true;
    plane.material.side = THREE.DoubleSide;
    plane.name= 'plane';
    ZW_SceneParent.add(plane);
}


var ZW_Person = null;


const forceTextureInitialization = function() {
  var material = new THREE.MeshBasicMaterial();
  material.transparent = true;
  var geometry = new THREE.PlaneBufferGeometry();
  var scene = new THREE.Scene();
  scene.add(new THREE.Mesh(geometry, material));
  var camera = new THREE.Camera();

  return function forceTextureInitialization(texture) {
    material.map = texture;
    ZW_Renderer.render(scene, camera);
  };
}();


function LoadGlbModel(url) {
  console.log(url);
  let fs = my.getFileSystemManager();
  //my.alert({content: url});
  let res1 = my.getStorageSync({ key: 'aj6' });

  if (false && res1.data) {
    // let fs = my.getFileSystemManager();
    // fs.readFile({
    //   filePath: res1.data.url,
    // });
    // clearInterval(ZW_Timer);
    // ZW_ProcessValue = 0.2;
    // OnProcess(ZW_ProcessValue);

    // ZW_Timer = setInterval(function () {
    //   ZW_ProcessValue += 0.01;
    //   OnProcess(ZW_ProcessValue);
    // }, 300);

    fs.readFile({
          filePath: res1.data.url,
          // encoding: 'utf8',
          success: result => {
            console.log('result');

            // clearInterval(ZW_Timer);
            // ZW_ProcessValue = 0.6;
            // OnProcess(ZW_ProcessValue);
            // ZW_Timer = setInterval(function () {
            //   ZW_ProcessValue += 0.01;
            //   OnProcess(ZW_ProcessValue);
            // }, 30);

            // OnProcess(0.3);
            //timestamp = (new Date()).getTime();

            //my.alert({ content: 'readfile finish' });
            //my.alert({ content: ((new Date()).getTime() - timestamp).toString() });



            //my.alert({ content: 'unzip finish' });

            var manager = new THREE.LoadingManager();
            var loader = new THREE.GLTFLoader(manager);

            loader.load(result.data, function (gltf) {

              // clearInterval(ZW_Timer);
              // ZW_ProcessValue = 0.7;
              // OnProcess(ZW_ProcessValue);
              // ZW_Timer = setInterval(function () {
              //   ZW_ProcessValue += 0.01;
              //   OnProcess(ZW_ProcessValue);
              // }, 300);

              var object = gltf.scene;

              var myscale = 1.0;
              object.scale.x = 1000 * myscale;
              object.scale.y = 1000 * myscale;
              object.scale.z = 1000 * myscale;

              // object.rotation.x = 1.80556;
              // object.rotation.y = 6.2938;
              // object.rotation.z = 0.3331546;

              object.scale.x = 4660;
              object.scale.y = 4660;
              object.scale.z = 4660;

              object.position.z -= 400000;

              // if (gltf.animations.length > 0) {
              //   var ZW_Mixer = new THREE.AnimationMixer(object);
              //   for (var i = 0; i < gltf.animations.length; i++) {
              //     if (i == 0 || i == 3 || i == 5)
              //       var personAnimation = ZW_Mixer.clipAction(gltf.animations[i]);
              //     personAnimation.play();
              //   }

              //   var clock = new THREE.Clock();
              //   var timer = setInterval(function () {
              //     var delta = clock.getDelta();
              //     ZW_Mixer.update(delta);
              //   }, 20);
              // }

              object.name = 'ZW_33';

              ZW_SceneParent.add(object);

              var picPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/aj-shadow3.png?t=1';


              if (ZW_Platform == 'Android') {
              } else {

              }

              //end

              for (var i = 1; i < 22; i++) {
                if (i == 15) {
                  continue;
                } else if (i < 10) {
                  ProcessTexture('AJ_00' + i + '_model');
                } else {
                  ProcessTexture('AJ_0' + i + '_model');
                }
              }

              object.visible = false;
            });


          }

        });
  } else {
    my.downloadFile({
      url: url,
      success: res => {
        //OnProcess(0.1);
        console.log('my.downloadFile success', res);
        let apFilePath = res.apFilePath;
        my.setStorageSync({
          key: 'aj6',
          data: {
            url: apFilePath
          }
        });

        //my.alert({ content: apFilePath });
        //my.alert({content: ((new Date()).getTime()-timestamp).toString()});
        fs.readFile({
          filePath: apFilePath,
          // encoding: 'utf8',
          success: result => {
            console.log('result');

            //timestamp = (new Date()).getTime();

            //my.alert({ content: 'readfile finish' });
            //my.alert({ content: ((new Date()).getTime() - timestamp).toString() });

            //OnProcess(0.3);

            //my.alert({ content: 'unzip finish' });

            var manager = new THREE.LoadingManager();
            var loader = new THREE.GLTFLoader(manager);

            loader.load(result.data, function (gltf) {

              //OnProcess(0.5);

              var object = gltf.scene;

              var myscale = 3;
              object.scale.x = 4660*10;
              object.scale.y = 4660*10;
              object.scale.z = 4660*10;

              object.rotation.x = Math.PI / 2;
              // object.rotation.y = Math.PI/2;
              //object.rotation.z = -Math.PI/18;

              object.rotation.y = -Math.PI/2;

              object.position.x = 20000;
              object.position.z -= 225000;

              // object.rotation.x = 1.672226;
              // object.rotation.y = 6.1605;
              // object.rotation.z = 0.3331546;

              // object.rotation.x = 1.60241;
              // object.rotation.y = 6.24776;
              // object.rotation.z = -0.31261;

              // object.rotation.x = 1.42788;
              // object.rotation.y = 6.7539;
              // object.rotation.z = 0.594953;

              // if (gltf.animations.length > 0) {
              //   var ZW_Mixer = new THREE.AnimationMixer(object);
              //   for (var i = 0; i < gltf.animations.length; i++) {
              //     if (i == 0 || i == 3 || i == 5)
              //       var personAnimation = ZW_Mixer.clipAction(gltf.animations[i]);
              //     personAnimation.play();
              //   }

              //   var clock = new THREE.Clock();
              //   var timer = setInterval(function () {
              //     var delta = clock.getDelta();
              //     ZW_Mixer.update(delta);
              //   }, 20);
              // }

              object.name = 'ZW_33';
              //object.visible = false;
              //  object.traverse(function (child) {

              //     if (child instanceof THREE.Mesh) {

              //       //child.material.color.setHex(0xff0000);
              //       //child.material.wireframe = true;
              //     }
              //   });

              //object.visible = false;

              ZW_SceneParent.add(object);


              // ZW_FinishSceneBox = new THREE.Box3().setFromObject(object, true);

              //     var material1 = new THREE.MeshBasicMaterial({
              //               color: 0xfafafa,
              //               wireframe:true
              //           });

              //        //  my.alert({content: ZW_FinishSceneBox});

              //     var mysize = new THREE.Vector3();
              //         ZW_FinishSceneBox.getSize(mysize);
              //         ZW_SceneSize = mysize.length();
              //         ResetViewPort();

       
              //start

              //var picPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/aj-shadow2.png?t=1';

              var picPath = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/aj-shadow3.png?t=1';


              if (ZW_Platform == 'Android') {
                

              } else {
               

              }

              //end

              ProcessTexture('Default_plastic1','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic1_baseColor.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic1_normal.png');
              ProcessTexture('Default_metal','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/metal_baseColor.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/metal_normal.png');
              ProcessTexture('Default_plastic2','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic2_baseColor.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic2_normal.png');
              ProcessTexture('Default_paint','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/paint_baseColor.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/paint_normal.png');
              ProcessTexture('map_Default','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/testpng1.png','http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/map_normal.png');

              InitUI();
              // for (var i = 1; i < 21; i++) {
              //   if (i == 15) {
              //     continue;
              //   } else if (i < 10) {
              //     ProcessTexture0('AJ_00' + i + '_model');
              //   } else {
              //     ProcessTexture0('AJ_0' + i + '_model');
              //   }
              // }

              object.visible = true;
            });


          }

        });
      },
      fail: res => {
        console.log('my.downloadFile fail', res);
      }
    });
  }
}

function ProcessTexture(nodeName,url1,url2) {
  showTime = (new Date()).getTime();

  var myobj = (ZW_SceneParent.getObjectByName('ZW_33')).getObjectByName(nodeName);
  

  if (ZW_Platform == 'Android') {
    var uvArray = myobj.children[0].geometry.attributes.uv.array;
    for (var i = 0; i < uvArray.length / 2; i++) {
      uvArray[i * 2 + 1] = 1.0 - uvArray[i * 2 + 1];
    }
    myobj.children[0].geometry.attributes.uv.needsUpdate = true;
   // myobj.children[0].visible = false;

      var planeMaterial = new THREE.MeshStandardMaterial({
      });


      planeMaterial.transparent = true;
      myobj.children[0].material = planeMaterial;
      planeMaterial.needsUpdate = true;

      var imgTex = new THREE.TextureLoader().load(canvas, url1,function( texture ) {
        myobj.children[0].material.map = texture;
        planeMaterial.needsUpdate = true;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });

      var imgTex1 = new THREE.TextureLoader().load(canvas, url2,function( texture ) {
        myobj.children[0].material.normalMap = texture;
        planeMaterial.needsUpdate = true;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });

      if(nodeName == 'Default_plastic1')
      {
        var imgTex2 = new THREE.TextureLoader().load(canvas, 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic1_occlusionRoughnessMetallic.png', function (texture) {
          //myobj.children[0].material.aoMap = texture;
          myobj.children[0].material.metalnessMap = texture;
          myobj.children[0].material.roughnessMap = texture;
          planeMaterial.needsUpdate = true;
        });
        //myobj.children[0].position.y += 0.01;
      }
      else if(nodeName == 'Default_metal')
      {
        var imgTex2 = new THREE.TextureLoader().load(canvas, 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/metal_occlusionRoughnessMetallic.png', function (texture) {
          myobj.children[0].material.aoMap = texture;
          myobj.children[0].material.metalnessMap = texture;
          myobj.children[0].material.roughnessMap = texture;
          planeMaterial.needsUpdate = true;
        });
      }else if(nodeName == 'Default_plastic2')
      {
        var imgTex2 = new THREE.TextureLoader().load(canvas, 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic2_occlusionRoughnessMetallic.png', function (texture) {
          //myobj.children[0].material.aoMap = texture;
          myobj.children[0].material.metalnessMap = texture;
          myobj.children[0].material.roughnessMap = texture;
          planeMaterial.needsUpdate = true;
        });
        planeMaterial.roughness = 2.0;
      }else if(nodeName == 'Default_paint')
      {
        var imgTex2 = new THREE.TextureLoader().load(canvas, 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/paint_occlusionRoughnessMetallic.png', function (texture) {
          //myobj.children[0].material.aoMap = texture;
          myobj.children[0].material.metalnessMap = texture;
          myobj.children[0].material.roughnessMap = texture;
          planeMaterial.needsUpdate = true;
        });
        planeMaterial.roughness = 2.0;
      }
      else
      {
        var imgTex2 = new THREE.TextureLoader().load(canvas, 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/map_occlusionRoughnessMetallic.png', function (texture) {
          //myobj.children[0].material.aoMap = texture;
          myobj.children[0].material.metalnessMap = texture;
          myobj.children[0].material.roughnessMap = texture;
          planeMaterial.needsUpdate = true;
        });
        planeMaterial.roughness = 2.0;
      }
      

      


  } else {
      var planeMaterial = new THREE.MeshPhysicalMaterial({

      });
      planeMaterial.transparent = true;
      myobj.children[0].material = planeMaterial;
      planeMaterial.needsUpdate = true;

      var textureid1 = gl.createTexture();
      var image1 = canvas.createImage();
      image1.src = url1;

      image1.onload = function () {
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, textureid1);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image1);

        var texture = new THREE.Texture();
        forceTextureInitialization(texture);
        var texProps = ZW_Renderer.properties.get(texture);
        texProps.__webglTexture = textureid1;


        planeMaterial.map = texture;
        planeMaterial.needsUpdate = true;
      }


      var textureid2 = gl.createTexture();
      var image2 = canvas.createImage();
      image2.src = url2;

      image2.onload = function () {
        gl.activeTexture(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, textureid2);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);

        var texture2 = new THREE.Texture();
        forceTextureInitialization(texture2);
        var texProps = ZW_Renderer.properties.get(texture2);
        texProps.__webglTexture = textureid2;

        planeMaterial.normalMap = texture2;
        planeMaterial.needsUpdate = true;
      }

      if(nodeName == 'Default_plastic1')
      {
        var textureid3 = gl.createTexture();
        var image3 = canvas.createImage();
        image3.src = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic1_occlusionRoughnessMetallic.png';

        image3.onload = function () {
          gl.activeTexture(gl.TEXTURE2);
          gl.bindTexture(gl.TEXTURE_2D, textureid3);

          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);

          var texture3 = new THREE.Texture();
          forceTextureInitialization(texture3);
          var texProps = ZW_Renderer.properties.get(texture3);
          texProps.__webglTexture = textureid3;

          //planeMaterial.aoMap = texture3;
          planeMaterial.metalnessMap = texture3;
          planeMaterial.roughnessMap = texture3;
          // planeMaterial.metalness = 1.0;
          // planeMaterial.roughness = 1.0;
          // planeMaterial.aoMapIntensity = 1.0;
        }
      }else if(nodeName == 'Default_metal'){
        var textureid3 = gl.createTexture();
        var image3 = canvas.createImage();
        image3.src = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/metal_occlusionRoughnessMetallic.png';

        image3.onload = function () {
          gl.activeTexture(gl.TEXTURE2);
          gl.bindTexture(gl.TEXTURE_2D, textureid3);

          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);

          var texture3 = new THREE.Texture();
          forceTextureInitialization(texture3);
          var texProps = ZW_Renderer.properties.get(texture3);
          texProps.__webglTexture = textureid3;

          //planeMaterial.aoMap = texture3;
          planeMaterial.metalnessMap = texture3;
          planeMaterial.roughnessMap = texture3;
        }
      }else if(nodeName == 'Default_plastic2'){
        var textureid3 = gl.createTexture();
        var image3 = canvas.createImage();
        image3.src = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/plastic2_occlusionRoughnessMetallic.png';

        image3.onload = function () {
          gl.activeTexture(gl.TEXTURE2);
          gl.bindTexture(gl.TEXTURE_2D, textureid3);

          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);

          var texture3 = new THREE.Texture();
          forceTextureInitialization(texture3);
          var texProps = ZW_Renderer.properties.get(texture3);
          texProps.__webglTexture = textureid3;

          //planeMaterial.aoMap = texture3;
          planeMaterial.metalnessMap = texture3;
          planeMaterial.roughnessMap = texture3;
        }
        planeMaterial.roughness = 2.0;
      }else if(nodeName == 'Default_paint'){
        var textureid3 = gl.createTexture();
        var image3 = canvas.createImage();
        image3.src = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/paint_occlusionRoughnessMetallic.png';

        image3.onload = function () {
          gl.activeTexture(gl.TEXTURE2);
          gl.bindTexture(gl.TEXTURE_2D, textureid3);

          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);

          var texture3 = new THREE.Texture();
          forceTextureInitialization(texture3);
          var texProps = ZW_Renderer.properties.get(texture3);
          texProps.__webglTexture = textureid3;

          //planeMaterial.aoMap = texture3;
          planeMaterial.metalnessMap = texture3;
          planeMaterial.roughnessMap = texture3;
        }
        planeMaterial.roughness = 2.0;
      }else{
        //myobj.children[0].visible = false;
        var textureid3 = gl.createTexture();
        var image3 = canvas.createImage();
        image3.src = 'http://morefun-active-1.oss-cn-shanghai.aliyuncs.com/starbucks2/model/20201109/map_occlusionRoughnessMetallic.png';

        image3.onload = function () {
          gl.activeTexture(gl.TEXTURE2);
          gl.bindTexture(gl.TEXTURE_2D, textureid3);

          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);

          var texture3 = new THREE.Texture();
          forceTextureInitialization(texture3);
          var texProps = ZW_Renderer.properties.get(texture3);
          texProps.__webglTexture = textureid3;

          //planeMaterial.aoMap = texture3;
          planeMaterial.metalnessMap = texture3;
          planeMaterial.roughnessMap = texture3;
        }
        planeMaterial.roughness = 2.0;
      }
    
  }
}

function ProcessTexture0(nodeName) {
  showTime = (new Date()).getTime();

  var myobj = (ZW_SceneParent.getObjectByName('ZW_33')).getObjectByName(nodeName.replace(/model/g,"M"));
  var urlBase = 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/nike/2020.10.25/GLB/';

  if (ZW_Platform == 'Android') {
    var uvArray = myobj.children[0].geometry.attributes.uv.array;
    for (var i = 0; i < uvArray.length / 2; i++) {
      uvArray[i * 2 + 1] = 1.0 - uvArray[i * 2 + 1];
    }
    myobj.children[0].geometry.attributes.uv.needsUpdate = true;


    if (nodeName != 'AJ_014_model' && nodeName != 'AJ_011_model' && nodeName != 'AJ_001_model' && nodeName != 'AJ_002_model' && 
    nodeName != 'AJ_010_model' && nodeName != 'AJ_013_model'&& nodeName != 'AJ_008_model'&&  nodeName != 'AJ_006_model' && 
      nodeName != 'AJ_003_model' && nodeName != 'AJ_004_model' && nodeName != 'AJ_005_model' && nodeName != 'AJ_016_model' && nodeName != 'AJ_012_model'&& nodeName != 'AJ_009_model') {
      var planeMaterial = new THREE.MeshPhysicalMaterial({
      });


      planeMaterial.transparent = true;
      myobj.children[0].material = planeMaterial;
      planeMaterial.needsUpdate = true;

      var imgTex = new THREE.TextureLoader().load(canvas, urlBase + nodeName + '_baseColor.png?t=3',function( texture ) {
        // imgTex.wrapS = imgTex.wrapT = 1000;

        // imgTex.minFilter = THREE.LinearFilter;
        myobj.children[0].material.map = texture;
        //texture.needsUpdate = true;
        planeMaterial.needsUpdate = true;

        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });

      var imgTex1 = new THREE.TextureLoader().load(canvas, urlBase + nodeName + '_normal.png?t=3',function( texture ) {
        myobj.children[0].material.normalMap = texture;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });

      var imgTex2 = new THREE.TextureLoader().load(canvas, urlBase + nodeName + '_occlusionRoughnessMetallic.png?t=3',function( texture ) {
        myobj.children[0].material.aoMap = texture;
        myobj.children[0].material.metalnessMap = texture;
        myobj.children[0].material.roughnessMap = texture;
        planeMaterial.needsUpdate = true;
	    });
      

      planeMaterial.metalness = 1.0;
      planeMaterial.roughness = 1.0;

      

    } else {
      var planeMaterial = new THREE.MeshPhysicalMaterial({
      });


      planeMaterial.transparent = true;
      myobj.children[0].material = planeMaterial;
      planeMaterial.needsUpdate = true;

      var imgTex = new THREE.TextureLoader().load(canvas, urlBase + nodeName + '_baseColor.png?t=1',function( texture ) {
        myobj.children[0].material.map = texture;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });

      var imgTex1 = new THREE.TextureLoader().load(canvas, urlBase + nodeName + '_normal.png?t=1',function( texture ) {
        myobj.children[0].material.normalMap = texture;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });


      if (nodeName == 'AJ_001_model') {
        //planeMaterial.metalness = 1.0;
        planeMaterial.roughness = 2.0;
      } else if (nodeName == 'AJ_014_model') {
        planeMaterial.color.setHex(0x666666);
      } else if (nodeName == 'AJ_013_model') {
        // planeMaterial.metalness = 1.0;
        planeMaterial.roughness = 1.0;
        planeMaterial.color.setHex(0xcccccc);
      } else if (nodeName == 'AJ_002_model') {
        // planeMaterial.metalness = 1.0;
        planeMaterial.roughness = 2.0;
        planeMaterial.color.setHex(0xbbbbbb);
      } else if (nodeName == 'AJ_003_model') {
        // planeMaterial.metalness = 1.0;
        planeMaterial.roughness = 2.0;
        planeMaterial.color.setHex(0xaaaaaa);
      } else if (nodeName == 'AJ_011_model') {
        planeMaterial.roughness = 2.0;
        //planeMaterial.color.setHex(0xaaaaaa);
      } else if (nodeName == 'AJ_016_model') {
        planeMaterial.roughness = 1.0;
        //planeMaterial.color.setHex(0xaaaaaa);
      } else if (nodeName == 'AJ_012_model') {
        planeMaterial.roughness = 2.0;
      } else if (nodeName == 'AJ_005_model') {
        //planeMaterial.metalness = 0.0;
        planeMaterial.roughness = 2.0;
        planeMaterial.color.setHex(0x555555);

      } else if (nodeName == 'AJ_009_model') {
        planeMaterial.roughness = 1.0;
        planeMaterial.color.setHex(0xaaaaaa);
      }else if (nodeName == 'AJ_010_model') {
        planeMaterial.roughness = 1.0;
        planeMaterial.color.setHex(0xaaaaaa);
      }else if (nodeName == 'AJ_004_model') {
        planeMaterial.roughness = 1.0;
        planeMaterial.color.setHex(0xcccccc);
      }if (nodeName == 'AJ_008_model') {
        planeMaterial.color.setHex(0xaaaaaa);
      } else if (nodeName == 'AJ_006_model') {
        planeMaterial.color.setHex(0xaaaaaa);
        planeMaterial.roughness = 2.0;
      }
    }
  } else {
    if(nodeName == 'AJ_005_model')
    {
      var planeMaterial = new THREE.MeshStandardMaterial({

      });
      planeMaterial.transparent = true;
      myobj.children[0].material = planeMaterial;
      planeMaterial.needsUpdate = true;

      var textureid1 = gl.createTexture();
      var image1 = canvas.createImage();
      image1.src = urlBase + nodeName + '_baseColor.png?t=2';

      image1.onload = function () {
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, textureid1);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image1);

        var texture = new THREE.Texture();
        forceTextureInitialization(texture);
        var texProps = ZW_Renderer.properties.get(texture);
        texProps.__webglTexture = textureid1;


        planeMaterial.map = texture;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
      }


      var textureid2 = gl.createTexture();
      var image2 = canvas.createImage();
      image2.src = urlBase + nodeName + '_normal.png?t=2';

      image2.onload = function () {
        gl.activeTexture(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, textureid2);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);

        var texture2 = new THREE.Texture();
        forceTextureInitialization(texture2);
        var texProps = ZW_Renderer.properties.get(texture2);
        texProps.__webglTexture = textureid2;

        planeMaterial.normalMap = texture2;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
      }

     // planeMaterial.metalness = 0.0;
      planeMaterial.roughness = 2.0;
      planeMaterial.color.setHex(0x555555);
    }else
    {
      var planeMaterial = new THREE.MeshPhysicalMaterial({

      });
      planeMaterial.transparent = true;
      myobj.children[0].material = planeMaterial;
      planeMaterial.needsUpdate = true;

      var textureid1 = gl.createTexture();
      var image1 = canvas.createImage();
      image1.src = urlBase + nodeName + '_baseColor.png?t=1';

      image1.onload = function () {
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, textureid1);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image1);

        var texture = new THREE.Texture();
        forceTextureInitialization(texture);
        var texProps = ZW_Renderer.properties.get(texture);
        texProps.__webglTexture = textureid1;


        planeMaterial.map = texture;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
      }


      var textureid2 = gl.createTexture();
      var image2 = canvas.createImage();
      image2.src = urlBase + nodeName + '_normal.png?t=2';

      image2.onload = function () {
        gl.activeTexture(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, textureid2);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);

        var texture2 = new THREE.Texture();
        forceTextureInitialization(texture2);
        var texProps = ZW_Renderer.properties.get(texture2);
        texProps.__webglTexture = textureid2;

        planeMaterial.normalMap = texture2;
        planeMaterial.needsUpdate = true;
        ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
      }

      if (nodeName != 'AJ_014_model' && nodeName != 'AJ_001_model' && nodeName != 'AJ_002_model' && nodeName != 'AJ_003_model' &&
         nodeName != 'AJ_013_model' && nodeName != 'AJ_011_model' && nodeName != 'AJ_016_model' && nodeName != 'AJ_004_model' && nodeName != 'AJ_006_model' && 
        nodeName != 'AJ_012_model' && nodeName != 'AJ_009_model'&& nodeName != 'AJ_010_model' && nodeName != 'AJ_008_model') {
        var textureid3 = gl.createTexture();
        var image3 = canvas.createImage();
        image3.src = urlBase + nodeName + '_occlusionRoughnessMetallic.png?t=1';

        image3.onload = function () {
          gl.activeTexture(gl.TEXTURE2);
          gl.bindTexture(gl.TEXTURE_2D, textureid3);

          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);

          var texture3 = new THREE.Texture();
          forceTextureInitialization(texture3);
          var texProps = ZW_Renderer.properties.get(texture3);
          texProps.__webglTexture = textureid3;

          planeMaterial.aoMap = texture3;
          planeMaterial.metalnessMap = texture3;
          planeMaterial.roughnessMap = texture3;
          planeMaterial.metalness = 1.0;
          planeMaterial.roughness = 1.0;
          planeMaterial.aoMapIntensity = 1.0;
        }
      } else {
        if (nodeName == 'AJ_014_model') {
          //planeMaterial.metalness = 1.0;
          planeMaterial.color.setHex(0x666666);

        } else if (nodeName == 'AJ_001_model') {
          //planeMaterial.metalness = 1.0;
          planeMaterial.roughness = 2.0;
          //planeMaterial.color.setHex(0x555555);
        } else if (nodeName == 'AJ_013_model') {
          // planeMaterial.metalness = 1.0;
          planeMaterial.roughness = 1.0;
          planeMaterial.color.setHex(0xcccccc);
        } else if (nodeName == 'AJ_002_model') {
          // planeMaterial.metalness = 1.0;
          planeMaterial.roughness = 2.0;
          planeMaterial.color.setHex(0xaaaaaa);
        } else if (nodeName == 'AJ_003_model') {
          // planeMaterial.metalness = 1.0;
          planeMaterial.roughness = 1.0;
          planeMaterial.color.setHex(0xaaaaaa);
        } else if (nodeName == 'AJ_011_model') {
          planeMaterial.roughness = 2.0;
          //planeMaterial.color.setHex(0xaaaaaa);
        } else if (nodeName == 'AJ_016_model') {
          planeMaterial.roughness = 2.0;
          //planeMaterial.color.setHex(0xaaaaaa);
        } else if (nodeName == 'AJ_012_model') {
          planeMaterial.roughness = 2.0;
          //planeMaterial.color.setHex(0xaaaaaa);
        }  else if (nodeName == 'AJ_009_model') {
          planeMaterial.roughness = 1.0;
          planeMaterial.color.setHex(0xaaaaaa);
        }else if (nodeName == 'AJ_010_model') {
          planeMaterial.roughness = 1.0;
          planeMaterial.color.setHex(0xaaaaaa);
        } else if (nodeName == 'AJ_004_model') {
          planeMaterial.roughness = 1.0;
          planeMaterial.color.setHex(0xcccccc);
        }else if (nodeName == 'AJ_008_model') {
          planeMaterial.color.setHex(0xaaaaaa);
        }else if (nodeName == 'AJ_006_model') {
          planeMaterial.color.setHex(0xaaaaaa);
          planeMaterial.roughness = 2.0;
          //planeMaterial.color.setHex(0xaaaaaa);
      }
      }
    }
    
  }
}

function disposeArray() {
  this.array = null;
}

var bFinish = false;
function OnProcess(value) {
  //my.alert({content: value.toString()});

  if(value < 1.01)
  {
    that.setData({
      processValue: parseInt(value * 100).toString() + '%',
      processWidth: 3.1 * value
    });
  }
  


  if (value > 0.999 && !bFinish) {
    bFinish = true;
    that.setData({
      bShowProcess: false,
      bTips: true,
      bBtn: true,
      bLightTips: true
    });

    ZW_SceneParent.getObjectByName('ZW_33').visible = true;

    ZW_SelectParent.visible = true;
  }
  
}


function ResetViewPort() {

  var center = new THREE.Vector3();

  ZW_FinishSceneBox.getCenter(center);

  var target = new THREE.Vector3();
  ZW_FinishSceneBox.getSize(target);
  ZW_SceneSize = target.length();

  ZW_normalCamera.position.copy(center);
  ZW_normalCamera.position.y -= ZW_SceneSize * ZW_PrimitiveViewDistance;

  ZW_normalCamera.near = ZW_SceneSize / 100;
  if(ZW_Platform != 'Android')
  {
    ZW_normalCamera.near = ZW_SceneSize / 10;
  }
  ZW_normalCamera.far = ZW_SceneSize * 1000000;
  ZW_normalCamera.updateProjectionMatrix();
  ZW_normalCamera.lookAt(center);

  ZW_normalCamera.up.x = 0;
  ZW_normalCamera.up.y = 0;
  ZW_normalCamera.up.z = 1;

  ZW_CenterNode0.position.copy(center);
  ZW_CameraNode.position.y = -ZW_SceneSize * ZW_PrimitiveViewDistance;

  ShowProcess1();

  ZW_CameraNode.position.x = 0;
  ZW_CameraNode.position.z = 0;

  var xvalue = ZW_CameraNode.position.x;
  var zvalue = ZW_CameraNode.position.z;
  ZW_CameraNode.position.x = 0;
  ZW_CameraNode.position.z = 0;

  ZW_CenterNode.updateMatrixWorld(true);
  ZW_Renderer.render(ZW_Scene, ZW_normalCamera);

  var camerapos1 = new THREE.Vector3(ZW_CameraNode.position.x, ZW_CameraNode.position.y, ZW_CameraNode.position.z);
  camerapos1.applyMatrix4(ZW_CenterNode.matrixWorld);

  ZW_normalCamera.position.copy(camerapos1);

  if (Math.cos(ZW_CenterNode.rotation.x) < 0) {
    ZW_normalCamera.up.x = 0;
    ZW_normalCamera.up.y = 0;
    ZW_normalCamera.up.z = -1;
  } else {
    ZW_normalCamera.up.x = 0;
    ZW_normalCamera.up.y = 0;
    ZW_normalCamera.up.z = 1;
  }
  ZW_normalCamera.updateProjectionMatrix();
  ZW_normalCamera.lookAt(ZW_CenterNode0.position);

  ZW_CameraNode.position.x = xvalue;
  ZW_CameraNode.position.z = zvalue;
  var camerapos1 = new THREE.Vector3(ZW_CameraNode.position.x, ZW_CameraNode.position.y, ZW_CameraNode.position.z+100000);
  camerapos1.applyMatrix4(ZW_CenterNode.matrixWorld);
  ZW_normalCamera.position.copy(camerapos1);

  ShowProcess1();
};

//添加普通的图片
function AddImage2(tag, width, height, url, maskurl, posX, posY, posZ,scale ,rotation, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    texture2: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
    uniform sampler2D texture2;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = vec4(texture2D(texture1, vec2(vUv.x,1.0-vUv.y)).rgb,texture2D(texture2, vec2(vUv.x,1.0-vUv.y)).r)*vec4(2.0,2.0,2.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = vec4(texture2D(texture1, vec2(vUv.x,vUv.y)).rgb,texture2D(texture2, vec2(vUv.x,vUv.y)).r)*vec4(2.0,2.0,2.0,alpha);}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.FrontSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = false;
  mesh1.material.depthWrite = false;
  mesh1.renderOrder = zIndex;

  mesh1.material.transparent = true;
  //mesh1.material.alphaTest = 0.2;

  // if(tag == 'back')
  // {
  //   mesh1.material.transparent = false;
  // }
  // else
  // {
  //   mesh1.material.transparent = false;
  // }
  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  mesh1.scale.x = scale;
  mesh1.scale.y = scale;
  mesh1.scale.z = scale;

  mesh1.rotation.z = rotation;
  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.LinearFilter;

    uniforms.texture1.value = imgTex;

    var imgTex2 = new THREE.TextureLoader().load(canvas, maskurl);
    imgTex2.minFilter = THREE.LinearFilter;

    uniforms.texture2.value = imgTex2;
    
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.DoubleSide;


    var image1 = document.createElementNS("","img");
    image1.src = url;
    var textureid0 = gl.createTexture();
    image1.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid0);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image1);
      uniforms.texture1.value = textureid0;
    }

    var image2 = document.createElementNS("","img");
    image2.src = maskurl;
    var textureid1 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE1);
      gl.bindTexture(gl.TEXTURE_2D, textureid1);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture2.value = textureid1;
    }

    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE1);
      gl.bindTexture(gl.TEXTURE_2D, textureid0);

      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid1);
    }
  }

  //(ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  ZW_SelectParent.add(mesh1);
  //ShowProcess();
}

//添加普通的图片
function AddImage3(tag, width, height, url, maskurl, posX, posY, posZ,scale ,rotation, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    texture2: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
    uniform sampler2D texture2;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = vec4((texture2D(texture1, vec2(vUv.x,1.0-vUv.y)).rgb),texture2D(texture2, vec2(vUv.x,1.0-vUv.y)).r-0.05)*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = vec4(texture2D(texture1, vec2(vUv.x,vUv.y)).rgb,texture2D(texture2, vec2(vUv.x,vUv.y)).r)*vec4(1.0,1.0,1.0,alpha);}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.FrontSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = false;
  mesh1.material.depthWrite = false;
  mesh1.renderOrder = zIndex;

  mesh1.material.transparent = true;
  mesh1.material.alphaTest = 0.2;

  // if(tag == 'back')
  // {
  //   mesh1.material.transparent = false;
  // }
  // else
  // {
  //   mesh1.material.transparent = false;
  // }
  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  mesh1.scale.x = scale;
  mesh1.scale.y = scale;
  mesh1.scale.z = scale;

  mesh1.rotation.z = rotation;
  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.LinearFilter;

    uniforms.texture1.value = imgTex;

    var imgTex2 = new THREE.TextureLoader().load(canvas, maskurl);
    imgTex2.minFilter = THREE.LinearFilter;

    uniforms.texture2.value = imgTex2;
    
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.DoubleSide;


    var image2 = document.createElementNS("","img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
  }

  //(ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  ZW_SceneParent.add(mesh1);
  //ShowProcess();
}

//添加普通的图片
function AddArrow(tag, width, height, url, posX, posY, posZ,scale ,rotation, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    color: {
      value: new THREE.Vector3(1.0, 1.0, 1.0)
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform vec3 color; \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(color,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y))*vec4(color,alpha);}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = false;
  mesh1.material.depthWrite = false;
  mesh1.renderOrder = zIndex;

  mesh1.material.transparent = true;

  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  mesh1.scale.x = scale;
  mesh1.scale.y = scale;
  mesh1.scale.z = scale;

  mesh1.rotation.z = rotation;
  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.DoubleSide;


    var image2 = document.createElementNS("","img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
  }

  //(ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  ZW_SelectParent.add(mesh1);
  //ShowProcess();
}

//添加普通的图片
function AddImage1(tag, width, height, url, posX, posY, posZ,scale ,rotation, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = true;
  // mesh1.material.depthWrite = false;
  // mesh1.renderOrder = zIndex;

  mesh1.material.transparent = true;

  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  mesh1.scale.x = scale;
  mesh1.scale.y = scale;
  mesh1.scale.z = scale;

  mesh1.rotation.z = rotation;
  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    //mesh1.material.side = THREE.DoubleSide;


    var image2 = document.createElementNS("","img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
     // gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      //gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
   // ShowProcess1();
  }

  //(ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  ZW_SelectParent.add(mesh1);
  //ShowProcess();
}

//添加普通的图片
function AddImage4(tag, width, height, url, posX, posY, posZ,scale ,rotation, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 0.45
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.8,1.8,1.8,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y))*vec4(1.8,1.8,1.8,alpha);}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = false;
  mesh1.material.depthWrite = false;
  mesh1.renderOrder = zIndex;

  mesh1.material.transparent = true;

  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  mesh1.scale.x = scale;
  mesh1.scale.y = scale;
  mesh1.scale.z = scale;

  mesh1.rotation.z = rotation;
  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.DoubleSide;


    var image2 = document.createElementNS("","img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
  }

  //(ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  ZW_SceneParent.add(mesh1);
  //ShowProcess();
}

//添加普通的图片
function AddImage(tag, width, height, url, posX, posY, posZ,zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = false;
  mesh1.material.depthWrite = false;
  mesh1.renderOrder = zIndex;

  mesh1.material.transparent = true;

  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.DoubleSide;


    var image2 = document.createElementNS("","img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
  }

  //(ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  ZW_SceneParent.add(mesh1);
  //ShowProcess();
}


//添加普通的图片
function AddShadow( width, height, url, posX, posY, posZ) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.BackSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  //mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = true;
  mesh1.material.depthWrite = true;

  mesh1.material.transparent = true;
  
  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.BackSide;


    var image2 = document.createElementNS("","img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
  }

  (ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
  //ZW_SceneParent.add(mesh1);
  //ShowProcess();
}

//添加普通的图片
function AddImage0( width, height, url, posX, posY, posZ) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.BackSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  
  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  //mesh1.name = tag;
  //mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = true;
  mesh1.material.depthWrite = true;

  mesh1.material.transparent = true;
  mesh1.rotation.x = Math.PI / 2;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.material.side = THREE.BackSide;

    var image2 = document.createElementNS("","img");
    image2.src = url;
    var textureid4 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid4;
      //ShowProcess();
    }
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
    }
  }

  (ZW_SceneParent.getObjectByName('ZW_33')).add(mesh1);
}

function SetBackColor(red, green, blue, alpha) {
  var hex = "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);

  ZW_BACK_COLOR = hex;

  if (typeof (alpha) == "undefined") {
    ZW_BACK_ALPHA = 1.0;
  } else {
    ZW_BACK_ALPHA = alpha;
  }

  ZW_Renderer.setClearColor(ZW_BACK_COLOR, ZW_BACK_ALPHA)
}

function ControlUpdate() {
  RotateCamera();
  ZoomCamera();
}

function ShowProcess1() {
  if(canvas.width < 400) {  //在修改webgl canvas的left后，canvas的尺寸有问题，需要重置
    canvas.width *= ZW_PixelRatio;
    canvas.height *= ZW_PixelRatio;
  }
  ZW_Renderer.setViewport(0, 0, ZW_Width1, ZW_Height1);
  ZW_Renderer.clear();
  ZW_Renderer.render(ZW_Scene, ZW_normalCamera);
}

function animate() {
  canvas.requestAnimationFrame(animate);
  ControlUpdate();
  TWEEN.update();
  // var timeLength = (new Date()).getTime()-showTime;
  // if(timeLength > HIDE_TIME && ZW_ProcessValue > 0.99)
  // {
  //   showTime = (new Date()).getTime();
  //   HideOrShowTab(true);
  //   TabState = true;
  // } 
  ShowProcess1();
}

//tab隐藏或者显示操作
function HideOrShowTab(value) {
  if(value)
  {
    if (!TabState) {
      // my.showToast({
      //   type: 'success',
      //   content: '显示Tab',
      //   duration: 1000,
      //   success: () => {

      //   },
      // });
    }
    
  }else 
  {
    if (TabState) {
      // my.showToast({
      //   type: 'success',
      //   content: '隐藏Tab',
      //   duration: 1000,
      //   success: () => {

      //   },
      // });
    }
  }

}


function getMouseOnScreen(pageX, pageY) {
  var vector = new THREE.Vector2();

  vector.set(
    (pageX) / canvas.width,
    (pageY) / canvas.height
  );

  return vector;
}

function getMouseOnCircle(pageX, pageY) {
  var vector = new THREE.Vector2();
  vector.set(
    ((pageX - canvas.width * 0.5) / (canvas.width * 0.5)),
    ((canvas.height + 2 * (0 - pageY)) / canvas.width)
  );

  return vector;
}

function ZoomCamera() {
  var factor;



  if (_state == STATE.TOUCH_ZOOM_PAN) {


    factor = _touchZoomDistanceEnd / _touchZoomDistanceStart;

    if (factor < 1.001 && factor > 0.999) return;

    //ZW_SceneParent.getObjectByName('tips').visible = false;
    // that.setData({
    //   bTips: false,
    //   bSize:true
    // });
    return;


    if (ZW_SceneParent.getObjectByName('ZW_33')) {
      ZW_SceneParent.getObjectByName('ZW_33').scale.x *= factor;
      ZW_SceneParent.getObjectByName('ZW_33').scale.y *= factor;
      ZW_SceneParent.getObjectByName('ZW_33').scale.z *= factor;

    }

    _touchZoomDistanceStart = _touchZoomDistanceEnd;

  }
}

function RotateCamera() {
  if (_state === STATE.TOUCH_ROTATE) {
    var moveDirection = new THREE.Vector3();
    var angle;

    moveDirection.set(_moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0);
    angle = moveDirection.length();


    //console.log(angle);
    if (angle && Math.abs(angle < 0.2)) {	//解决双指缩放时导致的角度突变

      //ZW_SceneParent.getObjectByName('tips').visible = false;
      that.setData({
        bTips: false,
        bSize:true
      });

      var xOffset = _moveCurr.x - _movePrev.x;
      var yOffset = _moveCurr.y - _movePrev.y;
      if (_state == STATE.TOUCH_ROTATE) {
        xOffset *= 4;
        yOffset *= 4;
      }

      if (ZW_SceneParent.getObjectByName('ZW_33')) {
        //  ZW_SceneParent.rotation.y += 3*xOffset;
        // ZW_SceneParent.rotation.x -= 3*yOffset;

        ZW_SceneParent.getObjectByName('ZW_33').rotation.y += 3*xOffset;
        //ZW_SceneParent.getObjectByName('ZW_33').rotation.x -= 3*yOffset;

        // if (ZW_SceneParent.getObjectByName('model' + CurrentIndex).rotation.x < -Math.PI / 2) ZW_SceneParent.getObjectByName('model' + CurrentIndex).rotation.x = -Math.PI / 2;
        // if (ZW_SceneParent.getObjectByName('model' + CurrentIndex).rotation.x > Math.PI / 2) ZW_SceneParent.getObjectByName('model' + CurrentIndex).rotation.x = Math.PI / 2;
      }

    }

    _movePrev.copy(_moveCurr);
  }
};

//组件旋转动画
function StartRotationAnimation(tag, startValue, endValue, time,delay, repeat) {
  if(!delay) delay = 0;
  if(!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = {x:startValue[0],y:startValue[1],z:startValue[2]};
  new TWEEN.Tween(coords) 
        .to({ x: endValue[0],y:endValue[1],z:endValue[2]}, time)
        .repeat(repeat)
        .easing(TWEEN.Easing.Quadratic.InOut) 
        .onUpdate(function() { 
            mymodel.rotation.x = coords.x;
            mymodel.rotation.y = coords.y;
            mymodel.rotation.z = coords.z;
            //ShowProcess();
        })
        .delay(delay)
        .start(); 
}

//组件大小动画
function StartScaleAnimation(tag, startValue, endValue, time,delay, repeat) {
  if(!delay) delay = 0;
  if(!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = {x:startValue[0],y:startValue[1],z:startValue[2]};
  new TWEEN.Tween(coords) 
        .to({ x: endValue[0],y:endValue[1],z:endValue[2]}, time)
        .repeat(repeat)
        .easing(TWEEN.Easing.Quadratic.InOut) 
        .onUpdate(function() { 
            mymodel.scale.x = coords.x;
            mymodel.scale.y = coords.y;
            mymodel.scale.z = coords.z;
            //ShowProcess();
        })
        .delay(delay)
        .start(); 
}

//组件位移动画
function StartPositionAnimation(tag, startValue, endValue, time,delay, repeat) {
  if(!delay) delay = 0;
  if(!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = {x:startValue[0],y:startValue[1],z:startValue[2]};
  new TWEEN.Tween(coords) 
        .to({ x: endValue[0],y:endValue[1],z:endValue[2]}, time)
        .repeat(repeat)
        .easing(TWEEN.Easing.Quadratic.InOut) 
        .onUpdate(function() { 
            mymodel.position.x = coords.x;
            mymodel.position.y = coords.y;
            mymodel.position.z = coords.z;
            //ShowProcess();
        })
        .delay(delay)
        .start(); 
}

//组件alpha动画
function StartAlphaAnimation(tag, startValue, endValue, time,delay, repeat) {
  if(!delay) delay = 0;
  if(!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = {x:startValue};
  new TWEEN.Tween(coords) 
        .to({ x: endValue}, time)
        .repeat(repeat)
        .easing(TWEEN.Easing.Quadratic.InOut) 
        .onUpdate(function() { 
            mymodel.material.uniforms.alpha.value = coords.x;
        })
        .delay(delay)
        .start(); 
}

//组件color动画
function StartColorAnimation(tag, startValue, endValue, time,delay, repeat) {
  if(!delay) delay = 0;
  if(!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = {x:startValue[0],y:startValue[1],z:startValue[2]};
  new TWEEN.Tween(coords) 
        .to({ x:endValue[0],y:endValue[1],z:endValue[2]}, time)
        .repeat(repeat)
        .easing(TWEEN.Easing.Quadratic.InOut) 
        .onUpdate(function() { 
            mymodel.material.uniforms.color.value = new THREE.Vector3(coords.x/255.0, coords.y/255.0, coords.z/255.0);
        })
        .delay(delay)
        .start(); 
}

function SetView(rotationX,rotationY)
{
  ZW_SceneParent.getObjectByName('ZW_33').rotation.y = rotationX;
  ZW_SceneParent.getObjectByName('ZW_33').rotation.x = rotationY;
  ShowProcess1();
}


function GetWindowSize() {
  var iOSModels = [ // 型号-1 windowWidth windowHeight 型号-2
    ["iPhone10", 375, 812, 3], // x
    ["iPhone11", 375, 812, 6], // x
    ["iPhone8", 375, 667, 1], // 6s
    ["iPhone7", 414, 736, 1], // 6p
    ["iPhone7,1", 414, 672, 1], // 6p
    ["iPhone9", 375, 667, 1], // 7
    ["iPhone9,2", 414, 736, 1], // 7p
    ["iPhone7", 375, 667, 2], // 6
  ];

  var re = [2];
  var info = my.getSystemInfoSync();
  //my.alert({content:info});

  if (info.platform == 'Android') {
    re[0] = info.windowWidth;
    re[1] = info.windowHeight;
  } else {
    re[0] = info.windowWidth;
    re[1] = info.windowHeight;



  }
  return re;
}


function GetClickedTag(event) {
  //my.alert({content: event});
  var mouse = new THREE.Vector2();
  if(PLATFORM == "TAOBAO")
  {
    mouse.x = ((event.touches[0].x*ZW_PixelRatio) / (ZW_Width1)) * 2 - 1;
    mouse.y = -((event.touches[0].y*ZW_PixelRatio) / (ZW_Height1)) * 2 + 1;
  }else
  {
    mouse.x = ((event.touches[0].pageX) / ZW_Width1) * 2 - 1;
    mouse.y = -((event.touches[0].pageY) / ZW_Height1) * 2 + 1;
  }

  ZW_raycaster.setFromCamera(mouse, ZW_normalCamera);

  var interArray = [];
  interArray.push(ZW_SelectParent.getObjectByName('closeBtn'));
  // interArray.push(ZW_SelectParent.getObjectByName('rect1'));
  // interArray.push(ZW_SelectParent.getObjectByName('rect2'));
  // interArray.push(ZW_SelectParent.getObjectByName('rect3'));

  var intersects = ZW_raycaster.intersectObjects(interArray, true);

  if (intersects[0]) {
    if(intersects[0].object.parent == ZW_SelectParent)
    {
      //console.log(intersects);
      return intersects[0].object.name;
    }else
    {
      return intersects[0].object.parent.name;
    }
    
  }
  return null;
}

function UpdateCup(baseUrl)
{
  //my.alert({content:baseUrl});
  var myobj = (ZW_SceneParent.getObjectByName('ZW_33')).getObjectByName('map_Default');
  

  if (ZW_Platform == 'Android') {
      // var planeMaterial = new THREE.MeshPhysicalMaterial({
      // });


      // planeMaterial.transparent = false;
      // myobj.children[0].material = planeMaterial;
      // planeMaterial.needsUpdate = true;

      var imgTex = new THREE.TextureLoader().load(canvas, baseUrl,function( texture ) {
        myobj.children[0].material.map = texture;
        //planeMaterial.needsUpdate = false;
        //ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
	    });


  } else {

      // var planeMaterial = new THREE.MeshPhysicalMaterial({

      // });
      // planeMaterial.transparent = true;
      // myobj.children[0].material = planeMaterial;
      // planeMaterial.needsUpdate = true;

      var textureid1 = gl.createTexture();
      var image1 = canvas.createImage();
      image1.src = baseUrl;

      image1.onload = function () {
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, textureid1);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image1);

        var texture = new THREE.Texture();
        forceTextureInitialization(texture);
        var texProps = ZW_Renderer.properties.get(texture);
        texProps.__webglTexture = textureid1;


        myobj.children[0].map = texture;
        myobj.children[0].needsUpdate = true;
        //ZW_ProcessNum--;
        //OnProcess(ZW_ProcessValue+(1.0-ZW_ProcessValue)*(40.0-ZW_ProcessNum)/40.0);
      }
  }
}